问题
I'm currently working with the spread syntax and ran into an unexpected issue.
The below snippet works (as expected), and doesn't throw any errors:
const arr = [1, 2, 3, 4] // create array of numbers
const copy = [...arr] // make a shallow copy of the array
copy.forEach(n => { // loop through array
console.log(n + 1);
});
However, if I remove the intermediate variable copy
, my code seems to throw an error:
const arr = [1, 2, 3, 4] // create array of numbers
[...arr].forEach(n => { // loop through array
console.log(n + 1);
});
As you can see, the above code snippet throws an error:
Uncaught SyntaxError: Unexpected token ...
Whereas the first snippet does not. Why is this happening? To my understanding I should be able to replace copy
with literal array it contains and have no issues (as I have done in the second snippet).
I expect the second snippet to behave as the first snippet, and not throw any errors.
Note: I'm aware that [...arr]
seems redundant in this case, I've simply used this to demonstrate my problem.
回答1:
Add a semicolon and it works perfectly.
const arr = [1, 2, 3, 4];
[...arr].forEach(n => {
console.log(n + 1);
});
The code was being evaluated without the newline - like this:
const arr = [1, 2, 3, 4][...arr]
Which resulted in your error.
来源:https://stackoverflow.com/questions/55841892/why-cant-i-remove-the-intermediate-variable-in-my-code