我有这个代码:
var users = [];
users.push({
username: "admin",
password: "admin"
});
this.showAllUsers = function() {
console.log(users);
};
this.addUser = function(user) {
if('username' in user && 'password' in user) {
users.push({
username: user.username,
password: user.password
})
}
else {
throw "Invalid object";
}
};
this.isExist = function(user) {
console.log(users.indexOf({
username: "admin",
password: "admin"
}));
};
为什么控制台日志总是打印 -1 ?用户数组包含带有属性用户名:“admin:”和密码:“admin”的对象的数组。
最佳答案
indexOf
方法使用严格等于 (===
)。当您使用 {foo: bar}
时,您将创建一个新的(唯一的)对象,该对象的计算结果不会严格等于数组中已有的任何内容。
您应该做的是迭代数组并使用函数通过深度相等来比较每个对象。简单地说,您可以使用类似的东西:
function match(arr, ref) { // Take an array and a reference object
return arr.filter(function (cur) { // Select any items in the array...
return Object.keys(ref).every(function (key) { // Where all keys...
return ref[key] === cur[key]; // Have the same value in the item and reference
});
});
}
关于javascript - JS中如何检查对象数组是否包含一个对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32462727/