我有学生名单。在列表中,一些学生可以处于事件状态,而其他学生可以处于非事件状态。
var allActive = [{id: 1, active: true}, {id: 2, active: true}, , {id: 3, active: true}];
var someNot = [{id: 4, active: true}, {id: 5, active: true}, , {id: 6, active: false}];
我想检查列表是否包含所有活跃的学生。简单的方法就是使用 for 循环
for(var index = 0, student; student = array[index]; index++){
if(stduent.active){
return false;
}
}
但是,我不想像这样创建额外的一段代码。我想使用像 forEach 这样的快速方法来检查数组是否所有元素都处于事件状态。使用一些内置数组函数可以快速完成此操作吗?
最佳答案
您可以使用方法every这样做。这是一个例子
var allActive = [{id: 1, active: true}, {id: 2, active: true}, , {id: 3, active: true}];
var someNot = [{id: 4, active: true}, {id: 5, active: true}, , {id: 6, active: false}];
console.log(allActive.every(entry=>entry.active)); // expected output: true
console.log(someNot.every(entry=>entry.active)); // expected output: false
关于javascript - 数组中的快速元素验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48398495/