我正在处理一个对象,该对象的键具有一个 bool 值。我正在尝试找出最有效的方法来检查从数组接收到的任何值在对象中是否等于 false 及其关联的键。
例如我有一个像这样的对象:
cars = {
bmw: true,
lexus: true,
audi: false,
mercedes: false
}
然后我会收到一个数组,例如:
allApproved(['bmw', 'audi']) // should return false
allApproved(['bmw', 'lexus']) // should return true
如果映射中键 false
的任何值,我希望我的函数返回 false。不管有多少,如果有的话我想返回 false。如果它们都是 true,我将返回 true。
最佳答案
The
every()
method tests whether all elements in the array pass the test implemented by the provided function.
var cars = {
bmw: true,
lexus: true,
audi: false,
mercedes: false
};
function allApproved(arr) {
return arr.every(function(el) {
return cars[el];
});
}
console.log(allApproved(['bmw', 'audi']));
console.log(allApproved(['bmw', 'lexus']));
关于javascript - 基于对象映射检查数组中的任何值是否为 false 的最有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38647290/