这对某些人来说可能看起来很愚蠢,但请尝试帮助我理解这里的意义,我目前正在学习 javascript,我的挑战之一如下
In countdown.js below, modify the while-loop with a conditional that will only allow a number to be printed if it is even. Your results should be the even numbers from 10 to 2 descending. Think carefully about how your code might decide if a number is even…
如果我使用下面的代码,我会得到答案 9、7、5、3、1,但如果我在注销中将它更改为 num + 1,它就会起作用。我认为减量会在注销后发生?
var num = 10;
while (num > 0) {
if (num % 2) {
console.log(num); // can't be right??????
}
num--;
}
最佳答案
当“num”中的值不能被 2 整除时,if
语句中的测试 num % 2
为真。 %
运算符给出除法后的余数,因此当余数不为零时,它为 true
。
如果您想要偶数,请使用 !(num % 2)
,当余数为零时将为 true
,或者更明确地 num % 2 === 0
。
关于javascript学习,while if,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25453895/