获取数组中项的索引可以使用以下方法:
function getIndex(arr, target) {
for (let i = 0; i < arr.length; i++) {
if (arr[i] === target) {
return i;
}
}
return -1; // 如果目标项不存在于数组中,返回-1
}
const array = [1, 2, 3, 4, 5];
const target = 3;
const index = getIndex(array, target);
console.log(index); // 输出:2
const array = [1, 2, 3, 4, 5];
const target = 3;
const index = array.indexOf(target);
console.log(index); // 输出:2
const array = [1, 2, 3, 4, 5];
const target = 3;
const index = array.findIndex(item => item === target);
console.log(index); // 输出:2
以上是获取数组中项的索引的常见方法。根据具体的应用场景和需求,选择合适的方法来获取索引。
领取专属 10元无门槛券
手把手带您无忧上云