As you are already using jQuery, you can use the grep function which is intended for searching an array:
(由于您已经在使用jQuery,因此可以使用旨在搜索数组的grep函数:)
var result = $.grep(myArray, function(e){ return e.id == id; });
The result is an array with the items found.
(结果是包含找到的项目的数组。)
If you know that the object is always there and that it only occurs once, you can just use result[0].foo
to get the value.(如果您知道对象始终存在并且只发生一次,则可以使用result[0].foo
来获取值。)
Otherwise you should check the length of the resulting array.(否则,您应该检查结果数组的长度。)
Example:(例:)
if (result.length === 0) {
// no result found
} else if (result.length === 1) {
// property found, access the foo property using result[0].foo
} else {
// multiple items found
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…