【问题标题】:Return countdown array javascript logic返回倒计时数组javascript逻辑
【发布时间】:2021-02-27 02:00:07
【问题描述】:

谁能告诉我这里的逻辑有什么问题?我试图返回一个从输入到函数的数字倒数的数组。到目前为止,我得到的是一个空数组,而不是 [7, 6, 5, 4, 3, 2, 1, 0](预期结果)。

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


console.log(countDown(7));

【问题讨论】:

  • number.length 数字没有.lengths。你只想要number
  • 啊当然。谢谢!

标签: javascript arrays for-loop


【解决方案1】:

而不是number.length(数字没有length 属性),您应该在两个地方都使用number。此外,在你的 for 循环规范中,使用 &lt;= number 否则你会落后一个。

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


console.log(countDown(7));

【讨论】:

    【解决方案2】:

    另一种方法是反转数组的键。

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

    【讨论】:

      猜你喜欢
      • 2016-01-28
      • 2014-04-27
      • 2023-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-14
      • 1970-01-01
      相关资源
      最近更新 更多