我正在尝试使用for循环来检查所有值是否均为真。
JS:
class Obj {
constructor(a) {
this.a = a;
}
check(x) {
//some code
return correct; //true or false
}
}
myList = [
new Obj(1),
new Obj(5),
new Obj(3)
]
var count = 0;
for (let x in myList) {
if (myList[x].check(0)) {
count++;
}
}
if (count == myList.length) {
console.log("pass");
} else {
console.log("fail");
}
是否有使用普通JS的更直接方法?
答案 0 :(得分:2)
class Obj {
constructor(a) {
this.a = a;
}
check(x) {
//some code
return true; //true or false
}
}
myList = [
new Obj(1),
new Obj(5),
new Obj(3)
]
if (myList.every(x => x.check(0))) {
console.log("pass");
} else {
console.log("fail");
}