问题:
I want the loop to count down starting with the user's input number all the way down to 0. For example, if the user puts in 10, it will count down from 10 to 0. I think I'm...
可以将文章内容翻译成中文,广告屏蔽插件会导致该功能失效:
问题:
I want the loop to count down starting with the user's input number all the way down to 0. For example, if the user puts in 10, it will count down from 10 to 0. I think I'm close but need a little help.
var userNum = Number(window.prompt("Enter number of your choice starting from 1"));
var i;
for (i = 0; i < userNum; i--) {
window.console.log(userNum[i]);
}
回答1:
You should make the loop start at userNum
and end at 0:
const userNum = Number(window.prompt("Enter number of your choice starting from 1"));
for (let i = userNum; i>=0 ; i--) {
console.log(i);
}
Also, if you decrement here, use >=
instead of <
. userNum[i]
doesn't work, it's a number not an iterable, Array-like struct.
回答2:
I think this is closer to what you want to achieve:
try {
var userNum = Number(prompt("Enter number of your choice starting from 1"));
if (userNum) {
for (; userNum > 0; userNum--) {
console.log(userNum);
}
}
} catch (e) {
console.log('Make sure you enter an integer value')
}
回答3:
Personally I prefer to use :
const userNum = Number(window.prompt("Enter number of your choice starting from 1"));
for(let x=1+userNum; x-->0;){
console.log('x',x);
}