2009-07-01 94 views
2
var allProductIDs = [5410, 8362, 6638, 6758, 7795, 5775, 1004, 1008, 1013, 1014, 1015, 1072, 1076, 1086, 1111, 1112, 1140]; 

lastProductID = 6758; 

由于某种原因,在我得到-1或我猜没有发现这个就相当于:问题的indexOf与JavaScript数组

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

我想不通的生活我为什么,因为它应该找到6758,那将是索引3.如果它是索引3,那么我应该找回6758我会想。

+0

对于它的价值,是-1表示未找到。 – Nosredna 2009-07-01 20:42:58

回答

5

.indexOf()用于字符串,而不是数组。

使用常规的Javascript,你必须遍历数组,直到找到匹配,或者使用jQuery的​​函数。

jQuery inArray()

+0

不错。没有意识到这一点。是不是有必要使用jQuery的简写。比如你可以使用$ .inArray()或类似的东西? – PositiveGuy 2009-07-01 20:45:09

+0

试过,但它无限循环,并给我一个-1每该死时间: 为(I = 0;我 0){addIndex = productIDs.length + 1; } alert(allProductIDs [jQuery.inArray(lastProductID)+ i]); productIDs [addIndex] = allProductIDs [jQuery.inArray(lastProductID)+ i]; } – PositiveGuy 2009-07-01 20:51:29

+0

它也在无限循环中抛出我的程序!奇怪的。 – PositiveGuy 2009-07-01 21:02:27

0

查看您的语法。你缺少尾架.. ']'

3
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; 
    } 
} 

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