Why can't I remove the intermediate variable in my code?

牧云@^-^@ 提交于 2019-12-12 12:58:21

问题


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

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