如何记录有多少可能性满足 if 语句 javascript

How to log how many possibilities fulfil the if statement javascript

const grades = [9, 8, 5, 7, 7, 4, 9, 8, 8, 3, 6, 8, 5, 6];
for (let i = 0; i < grades.length; i++) {
  if (grades[i] >= 8) {
    console.log(grades[i])
  }
}

我正在尝试记录数组中有多少项满足条件。我正在寻找的输出是:6(因为其中 6 个数字等于或大于 8)

尝试过

设计数 = 0; 对于(设 i = 0;i < grades.length;i++){

如果(成绩[i]>= 8){ 计数++

console.log(count)

}

}

您可以调用 Array.filter 来创建一个仅包含满足条件的项目的新数组。然后,您可以根据需要使用数组的长度。像这样

const grades = [9, 8, 5, 7, 7, 4, 9, 8, 8, 3, 6, 8, 5, 6];
const gradesThatPassCondition = grades.filter(grade => grade > 6);
console.log(gradesThatPassCondition.length);
function countGreaterThan8(grades){
    // initialize the counter
    let counter = 0;
    for (let i = 0; i < grades.length; i++) {

      // if the condition satisfied counter will be incremented 1
      if (grades[i] >= 8) {
        counter++;
      }
    }
    return counter;
}

const grades = [9, 8, 5, 7, 7, 4, 9, 8, 8, 3, 6, 8, 5, 6];
console.log(countGreaterThan8(grades)); // 6