在下面的for loop
中,我试图使用 decremental 进行循环,以返回中指定整数范围内的所有偶数升序。
我该如何向后循环并返回或控制台以升序顺序依次记录介于0和11之间的所有偶数??
//decremental "for loop" that logs 2, 4, 6, 8, 10 in to the console
for (let i = 0; i < 11; i--) {
if (i !==3,5,7,9){
console.log(i); }
}
答案 0 :(得分:0)
以上代码段中的当前for loop
从0
开始,并从此开始递减,从而导致负值索引。
只需在11
处开始循环的索引并从该索引开始递减,同时使用 index % 2 == 0
这样的模运算符检查每个索引是否为偶数。< / p>
将所有偶数记录为单个字符串:
如果值是偶数,则将其附加到称为“ even
”的字符串的开头,然后只需将even
数组中的每个元素记录到您的这样的控制台:
var even = ""; //assign an empty string for your even numbers
for (let i = 11; i > 0; i--) { // loop through all numbers between 0 and 11
if (i % 2 == 0) { // check each loop value if it's an even number or not
even = i + ", " + even; // append the even numbers to the start of your "even" string
}
}
// log each element in your "even" string to the console
console.log(even);
将每个升序偶数记录为单独的整数:
如果该值是偶数,则使用unshift()方法将其推入一个称为“ even
”的数组的开头,然后只需将每个元素记录到像这样even
到您的控制台数组:
var even = []; //assign an empty array for your even numbers
for (let i = 11; i > 0; i--) { // loop through all numbers between 0 and 11
if (i % 2 == 0) { // check each loop value if it's an even number or not
even.unshift(i); // add the even numbers to the start of your "even" array using the unshift() method
}
}
// log each value in your "even" array to the console
even.forEach(e => console.log(e));