我發現這個簡單的“for回圈”練習。
使用 for 回圈列印直到并包括 n 的所有偶數。不包括 0。
let n1 = 22; // Example output: // 2 4 6 8 10 12 14 16 18 20 22 OR each item on a new line
我找到了解決這個問題的方法,但我認為它一點也不優雅。
這是我的代碼:
let n1 = 22;
for (let i = 0; i < n1; i ){
let b = i * 2;
if (b <= n1){
if (b == 0) {} else
{ console.log('Count',b);}
};
};
我該如何改進它?
uj5u.com熱心網友回復:
用二數來算:
for (let i=2; i <= 22; i =2) {
console.log('Count', i);
}
uj5u.com熱心網友回復:
for (let i=2; i <= 22; i =2) {
console.log(i);
}
一切順利
uj5u.com熱心網友回復:
這里使用while回圈:
const count = { index: 0, n1: 22 }
while(count.index < count.n1) {
console.log('Count', count.index = 2)
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/481507.html
標籤:javascript for循环
