Why doesn't this for loop work when I simple change two expression's order [duplicate]

允我心安 提交于 2021-02-10 05:57:09

问题


For the following fibonacci function, it works as expected:

function fibonacci(n) {
  var nums = []
  var a = b = 1
  for (let i = 0; i < n; i++) {
    [a, b] = [b, a + b]
    nums.push(a)
  }
  return nums
}

console.log(fibonacci(5));
// outputs: [1,2,3,5,8]

but after I changed two statements' order, it doesn't work:

function fibonacci(n) {
  var nums = []
  var a = b = 1
  for (let i = 0; i < n; i++) {
    nums.push(a)
    [a, b] = [b, a + b]
  }
  return nums
}

console.log(fibonacci(5));
// outputs: [1,1,1,1,1]

What's wrong with it?


回答1:


It's because you left out the semicolon at the end of the line

nums.push(a)

So it's merging the two lines into:

nums.push(a)[a, b] = [b, a + b]

This doesn't reassign the a and b variables, it's indexing an array.

You should really get out of the bad habit of omitting semicolons. Javascript allows it, but as you see in this example it doesn't always infer the statement breaks where you assume they would be.

function fibonacci(n) {
  var nums = [];
  var a = b = 1;
  for (let i = 0; i < n; i++) {
    nums.push(a);
    [a, b] = [b, a + b];
  }
  return nums;
}

console.log(fibonacci(5));
// outputs: [1,1,1,1,1]


来源:https://stackoverflow.com/questions/40601173/why-doesnt-this-for-loop-work-when-i-simple-change-two-expressions-order

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!