Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript .indexOf not working on an int array

Code:

function showlayer(name){
    var size = js_array.length
    var index = js_array.indexOf(name);
    var plusOne = js_array[index+1];
    document.write("" + name + "<br />" + js_array + "<br />" + index + "<br />" +
                   plusOne + "<br />" )
    ...
}

Output:

301
300,299,301,290,303,304,302,310,291,306,308,305,307,292,294,295,309
-1
300

All possible values of name are in the array, but for some reason indexOf() never finds them. Whats up?

like image 314
gta0004 Avatar asked Jan 29 '13 20:01

gta0004


People also ask

Does indexOf work on arrays?

indexOf() 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.

How to get index of an element in an array in js?

To find the position of an element in an array, you use the indexOf() method. This method returns the index of the first occurrence the element that you want to find, or -1 if the element is not found.

How to use array indexOf?

Definition and Usage The indexOf() method returns the first index (position) of a specified value. The indexOf() method returns -1 if the value is not found. The indexOf() method starts at a specified index and searches from left to right. By default the search starts at the first element and ends at the last.

Can you index an integer in JavaScript?

Yes, technically array-indexes are strings, but as Flanagan elegantly put it in his 'Definitive guide': "It is helpful to clearly distinguish an array index from an object property name. All indexes are property names, but only property names that are integers between 0 and 232-1 are indexes."


1 Answers

Try this instead:

...
var index = js_array.indexOf(parseInt(name, 10)); // so that it does not try to compare strings...
...
like image 75
Naftali Avatar answered Oct 18 '22 02:10

Naftali