got that code:
var itemGrid = [3,4,2,11,1,3,5,8,6]; var a = itemGrid.indexOf(0); a is everytime -1. It should be 3. What did I do wrong?
fiddle: http://jsfiddle.net/okg9g4tt/
got that code:
var itemGrid = [3,4,2,11,1,3,5,8,6]; var a = itemGrid.indexOf(0); a is everytime -1. It should be 3. What did I do wrong?
fiddle: http://jsfiddle.net/okg9g4tt/
There is a misunderstanding.
indexOf will not get the element at index 0, it will
return the first index at which a given element can be found in the array, or -1 if it is not present.
If you want the element at index 0, you should simply do itemGrid[0]
This is becuase 0 is not a value in your initial array. The function then returns -1. (see docs)
The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.
To return the value at index 0, use itemGrid[0]
IMPORTANT NOTE:
.indexOf() is not supported by IE8 and below so pay attention if you plan to support these browsers.
indexOf returns index of found element. Here -1 is returned because 0 is not found in your array.
NOTE: indexOf will get you the position of the element if found, so when you do itemGrid.indexOf(0); , it means you are looking for the position of the element '0' which is not present in your array and hence it is returning -1
IndexOf(IndexOf<T>(T[], T))
Searches for the specified object and returns the index of its first occurrence in a one-dimensional array.
your example tries to find the first indexof 0 returning -1, meaning no 0's where found.
To return the first index in your array use the indexer ItemGrid[0]
indexOfwill give you the index of(!) the element0... which is not part of the array, so the result is-1. If you want to get the zero index element of the array, just dovar a = itemGrid[0]