【问题标题】:js destructuring assignment not work in while loopjs解构赋值在while循环中不起作用
【发布时间】:2019-07-18 00:58:30
【问题描述】:

[a,b] = [b, a+b] 这里不行,a b 总是 0 和 1。

如果使用临时变量来交换值,则可以。

function fibonacciSequence() {
  let [a, b, arr] = [0, 1, []]
  while (a <= 255) {
    arr.concat(a)
    [a, b] = [b, a + b]
    console.log(a, b) // always 0 1
  }
}
console.log(fibonacciSequence())

【问题讨论】:

  • 你想要的输出是什么?
  • 你认为arr.concat(a)[a, b] 是什么意思?

标签: javascript destructuring


【解决方案1】:

问题在于自动分号插入没有达到您的预期。它不是在

之间添加分号
arr.concat(a)

[a, b] = [b, a + b]

所以它被视为你写的

arr.concat(a)[a, b] = [b, a + b]

明确添加所有分号,您会得到正确的结果。

function fibonacciSequence() {
  let [a, b, arr] = [0, 1, []];
  while (a <= 255) {
    arr.concat(a);
    [a, b] = [b, a + b];
    console.log(a, b); // always 0 1
  }
}
console.log(fibonacciSequence())

【讨论】:

    【解决方案2】:

    您也可以使用以下功能:

        function fibonacciSequence() {
          let [a, b] = [0, 1];
          while (a <= 255) {
    
           b = a + b;
           a = b - a;
           console.log(a,b);
          }
        }
        fibonacciSequence();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-25
      • 2017-02-06
      • 2013-02-17
      • 2010-11-11
      • 1970-01-01
      • 2015-03-22
      • 2011-10-19
      • 1970-01-01
      相关资源
      最近更新 更多