2009-07-01 96 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);