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

Problem with indexOf on JavaScript array - Stack Overflow

programmeradmin0浏览0评论
var allProductIDs = [5410, 8362, 6638, 6758, 7795, 5775, 1004, 1008, 1013, 1014, 1015, 1072, 1076, 1086, 1111, 1112, 1140];

lastProductID = 6758;

for some reason I get a -1 or I guess which is equivalent to not found for this:

alert(allProductIDs[allProductIDs.indexOf(lastProductID));

I can't figure out for the life of my why because it should find 6758 and that would be index 3. If it's index 3 then I should get back 6758 I would think.

var allProductIDs = [5410, 8362, 6638, 6758, 7795, 5775, 1004, 1008, 1013, 1014, 1015, 1072, 1076, 1086, 1111, 1112, 1140];

lastProductID = 6758;

for some reason I get a -1 or I guess which is equivalent to not found for this:

alert(allProductIDs[allProductIDs.indexOf(lastProductID));

I can't figure out for the life of my why because it should find 6758 and that would be index 3. If it's index 3 then I should get back 6758 I would think.

Share Improve this question asked Jul 1, 2009 at 20:35 PositiveGuyPositiveGuy 47.8k112 gold badges314 silver badges479 bronze badges 1
  • 1 For what it's worth, yes -1 means not found. – Nosredna Commented Jul 1, 2009 at 20:42
Add a ment  | 

3 Answers 3

Reset to default 5

.indexOf() is used for strings, not arrays.

Using regular Javascript you'll have to loop through the array until you find a match, or use the inArray() function of jQuery.

jQuery inArray()

var allProductIDs = [5410, 8362, 6638, 6758, 7795, 5775, 1004, 1008, 1013, 1014, 1015, 1072, 1076, 1086, 1111, 1112, 1140];

lastProductID = 6758;

for (i in allProductIDs)
{
    if (allProductIDs[i] == lastProductID) {
        alert(allProductIDs[i] + " is at index " + i);
        break;
    }
}

or

i = $.inArray(lastProductID, allProductIDs)
alert(allProductIDs[i] + " is at index " + i);

Check your syntax too. You are missing an end bracket ..']'

发布评论

评论列表(0)

  1. 暂无评论