在JQuery中,我有一个变量被声明为二维数组。在我的例子中,数组的第一个维度有4个元素:
length: 4
[0]: {...}
[1]: {...}
[2]: {...}
[3]: {...}
4个元素中的每一个都包含一个唯一的键和一个值,例如:
Key: "Some key"
Value: "This is some value"
我想做的是搜索数组,并在key等于例如"Some key"的地方获得Value。使用JQuery可以在一两行中优雅地完成这项工作吗?
确定:
$.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:
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"
}
});
(some
和every
可以在IE8等上匀场。)