通常我们对一个数组中的数据进行为真时,一般我们做法是:
const fruits = [
{ name: 'apple', color: 'red' },
{ name: 'banana', color: 'yellow' },
{ name: 'grape', color: 'purple' }
];
function test() {
let isAllRed = true;
// 条件:所有水果都是红色
for (let f of fruits) {
if (!isAllRed) break;
isAllRed = (f.color == 'red');
}
console.log(isAllRed);
}
test() // false
此种方法简单,逻辑一目了然,缺点是行数多,维护成本高。我们有更经济,易维护的方法
const fruits = [
{ name: 'apple', color: 'red' },
{ name: 'banana', color: 'yellow' },
{ name: 'grape', color: 'purple' }
];
function test() {
const isAllRed = fruits.every(f => f.color == 'red');
console.log(isAllRed); // false
}
Array.every(如果回调函数的每一次返回都为 truthy 值,返回 true ,否则返回 false。)
一行Array.every,替代繁重的for循环遍历,还不赶快用起来?
想了解更多?点击 Array.prototype.every()