如何在javascript数组中找到包含多个键/值对的对象?

时间:2015-07-15 05:46:46

标签: javascript arrays object

假设:

var objects_found = [];
var entry = {any_number:77, any_text:"P1"}; // note: both primitive types
objects_found.push(entry);

..为什么 - 控制台日志记录显示正确存储这些键/值对 - 以下内容:

if (entry in objects_found) { ... }; // never fires
if (!(entry in objects_found)) { ... }; // always fires

除了讨论here)循环数组外,还有一个简单的解决方法吗?

1 个答案:

答案 0 :(得分:2)

使用Array.prototype.indexOf

if (objects_found.indexOf(entry) !== -1) {
    // `entry` is in `objects_found`
} else {
    // not in the array
}

Fiddle