2014-10-19 58 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" 
    } 
});