简体   繁体   中英

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 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]); }

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.

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); }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM