How to decrement a for loop in JavaScript based upon a number that a user enters into a prompt?

问题: 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);
}

  • 发表于 2019-02-21 01:42
  • 阅读 ( 139 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除