我正在尝试使用 for 循环来检查所有值是否均为 true。
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 来做到这一点?
最佳答案
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");
}
关于javascript - for循环检查JS的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55973242/