问题
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