1

I understand that the array.indexOf() function gives you the index of a particular element in an Array.

If an Element is found, Array.indexOf() returns the position of that element in the array.

If the Element is not found, Array.indexOf() would return -1 as an output.

However, I am trying to understand the output in the following scenario.

var arr = [2,3,4,5,7,5];

for(var i =0;i<arr.length;i++) {
  console.log(arr.indexOf(i));
}

Output :

-1 -1 0 1 2 3

According to the Logic, When it finds 2 and 3 it should not return -1 in the console.

Going by the sequence of output i understand that the array index 0 starts at element 4 ?? Why is this happening?

I am just trying to understand what is going on?? Any Help would be highly appreciated.

2
  • 1
    Your loop starts at 0 - the index of 0 is -1, the index of 1 is -1, and the index of 2 is 0, etc. Commented Jan 13, 2017 at 21:08
  • @Daniel Understood!! Commented Jan 13, 2017 at 21:11

1 Answer 1

3

-1 means the value was not found in the target array. The 0 means that the value was found at position 0 in the array and so on.

So when i = 2 in the loop it is finding the value 2 at position 0 in arr.

For reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.