2014-10-19 59 views
0

在JQuery中,我有一個聲明爲二維數組的變量。在我的例子數組的第一個維度有4個元素:在JQuery中搜索二維數組

length: 4 
[0]: {...} 
[1]: {...} 
[2]: {...} 
[3]: {...} 

每4個元素包含一個唯一的密鑰和值,例如像:

Key: "Some key" 
Value: "This is some value" 

我想怎麼辦,搜索數組,並獲取Value等於例如「Some key」的值。這可以用JQuery在一行或兩行中完成嗎?

+0

注意,如果元件具有相同的鍵' Key'和'Value',它聽起來像是* objects *,而不是數組,所以你擁有的是一個對象數組,而不是一個二維數組。 (反正JavaScript並不是真的有二維數組,但是......) – 2014-10-19 21:44:38

回答

2

肯定的:

$.each(theArray, function(index, entry) { 
    // Use entry.Key and/or entry.Value here 
}); 

或者沒有的jQuery在任何現代的瀏覽器:

theArray.forEach(function(entry) { 
    // Use entry.Key and/or entry.Value here 
}); 

forEach可以在IE8被勻和這樣的。)

如果你想停在第一場比賽,然後:

$.each(theArray, function(index, entry) { 
    if (/* Use entry.Key and/or entry.Value here*/) { 
     return false; // Ends the "loop" 
    } 
}); 

或者沒有的jQuery在任何現代的瀏覽器:(someevery可以在IE8被墊高和這樣)

theArray.some(function(entry) { 
    if (/* Use entry.Key and/or entry.Value here*/) { 
     return true; // Ends the "loop" 
    } 
}); 

theArray.every(function(entry) { 
    if (/* Use entry.Key and/or entry.Value here*/) { 
     return false; // Ends the "loop" 
    } 
});