You are checking the first element (index i = 0
) against the target. If they don't match, you call return -1
. return
immediately exists the function. You probably want to place your return after the loop.
let array = [1, 2, 3, 4, 5, 6, 7, 8, 9];
let target = 5;
function search() {
for (let i = 0; i < array.length; i++) {
if (array[i] === target) {
console.log(true);
return i;
}
}
console.log(false);
return -1;
}
search();
Furhtermore it's not necessary to do array.indexOf
inside the loop, because if array[i] == target
you already have the correct index i
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…