Standard
Standard

Reputation: 1512

array.indexOf is just -1

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/

Upvotes: 0

Views: 95

Answers (9)

AmmarCSE
AmmarCSE

Reputation: 30557

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]

Upvotes: 5

Shane
Shane

Reputation: 790

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]

Upvotes: 0

Megh Vidani
Megh Vidani

Reputation: 635

"0" is not present in the Array, so it will return -1.

Upvotes: 0

kakon
kakon

Reputation: 721

0 is not an element of that array. So its index is being returned as -1;

probably you want to have itemGrid[0] which will return 3

Upvotes: 2

ozil
ozil

Reputation: 7117

a is everytime -1. It should be 3. What did I do wrong?

var itemGrid = [3,4,2,11,1,3,5,8,6];
var a = itemGrid[0];   // 3

Upvotes: 1

Strikers
Strikers

Reputation: 4776

array.indexOf(n) returns the position of n in the array. if n is not in the array it returns -1. in this case 0 is not present so -1.

while array[n] returns value present at nth position in the array

Upvotes: 0

Abhinav
Abhinav

Reputation: 8168

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

Upvotes: 1

Ted Nyberg
Ted Nyberg

Reputation: 7391

Should be:

itemGrid[0]

indexOf(0) would return the position of the value 0 in the array, but there is no 0 in the array.

Upvotes: 1

Yotam Omer
Yotam Omer

Reputation: 15356

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.

Upvotes: 3

Related Questions