简体   繁体   中英

Return countdown array javascript logic

Can someone tell me what's wrong with my logic here? I'm trying to return an array that counts down from the number input to the function. As of now, I'm getting an empty array, as opposed to [7, 6, 5, 4, 3, 2, 1, 0] (the expected result).

 const countDown = (number) => { let arrayCount = []; for (let i = 0; i < number.length; i++) { arrayCount.push(number.length - i) } return arrayCount } console.log(countDown(7));

Rather than number.length (numbers don't have a length property), you should just use number in both places. Also, inside your for loop specification, use <= number or else you'll be off by one.

 const countDown = (number) => { let arrayCount = []; for(let i = 0; i <= number; i++) { arrayCount.push(number - i) } return arrayCount } console.log(countDown(7));

An alternative method is to reverse the keys of an array.

 const countDown = number => [...Array(number + 1).keys()].reverse(); console.log(countDown(7));

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