3

I'm trying to recreate the indexOf array method in JavaScript. For the life of me, I can't figure out why the following isn't working:

function indexOf(array, value) {
  for (let i = 0; i < array.length; i++) {
    if (array[i] === value) {
      return i;
    }
    return -1;
  }
}

For example:

indexOf([1,2,1,3], 2) // should return 1

Thanks in advance.

4

1 回答 1

4

您只需要移动循环的return -1外部即可。for

function indexOf(array, value) {
    for (let i = 0; i < array.length; i++) {
        if (array[i] === value) {
            return i;
        }
    }

    return -1;
}

console.log(indexOf([1, 2, 1, 3], 2));
console.log(indexOf([1, 2, 1, 3], 4));

于 2018-11-09T02:34:29.987 回答