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; for (讓 i = 0; i < grades.length; i ) {
if (grades[i]>= 8){ count
console.log(count)
}
}
uj5u.com熱心網友回復:
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
uj5u.com熱心網友回復:
您可以呼叫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);
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/453584.html
標籤:javascript for循环 if 语句
