Javascript .indexOf not working on an int array
Asked Answered
A

1

9

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?

Appleton answered 29/1, 2013 at 20:56 Comment(4)
Are you comparing numbers to strings?Stadium
This isn't the problem you are specifically seeing here, but it is worth pointing out that Array.indexOf() isn't available on IE8 and lower. See here: #2790501.Irrevocable
@Irrevocable Yeah I know. Hope it won't be too much of an issueAppleton
That stackoverflow link has a polyfill to add support for Array.indexOf() to IE6-8 if you need it. I prefer to only support IE9 and up now-a-days, but there are still a lot of IE8 people out there.Irrevocable
S
29

Try this instead:

...
var index = js_array.indexOf(parseInt(name, 10)); // so that it does not try to compare strings...
...
Stoup answered 29/1, 2013 at 20:58 Comment(6)
@Appleton happy to help ^_^Stoup
@gta0004: Apparently, name is not an int.Stadium
@Stadium hehe that is most probably true.Stoup
@Stadium look at the output. 301 = name. so idkAppleton
@Appleton output typeof name and your shall see ^_^Stoup
Or, simply cast the key to Int: array.indexOf(+name).Builder

© 2022 - 2024 — McMap. All rights reserved.