最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript .indexOf not working on an int array - Stack Overflow

programmeradmin1浏览0评论

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?

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?

Share Improve this question asked Jan 29, 2013 at 20:56 gta0004gta0004 5084 gold badges11 silver badges29 bronze badges 4
  • Are you comparing numbers to strings? – SLaks Commented Jan 29, 2013 at 20:57
  • 1 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: stackoverflow.com/questions/2790001/…. – pseudosavant Commented Jan 29, 2013 at 21:45
  • @pseudosavant Yeah I know. Hope it won't be too much of an issue – gta0004 Commented Jan 29, 2013 at 23:47
  • 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. – pseudosavant Commented Jan 30, 2013 at 17:31
Add a comment  | 

1 Answer 1

Reset to default 29

Try this instead:

...
var index = js_array.indexOf(parseInt(name, 10)); // so that it does not try to compare strings...
...
发布评论

评论列表(0)

  1. 暂无评论