循环检查JS的最佳方法

时间:2019-05-03 15:48:13

标签: javascript

我正在尝试使用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的更直接方法?

1 个答案:

答案 0 :(得分:2)

使用Array.prototype.every()

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");
}

相关问题