为什么我不能在代码中删除中间变量? [英] Why can't I remove the intermediate variable in my code?
问题描述
我目前正在使用传播语法,但遇到了意外问题.
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);
});
但是,如果我删除中间变量copy
,我的代码似乎会抛出错误:
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:
未捕获到的SyntaxError:意外令牌...
Uncaught SyntaxError: Unexpected token ...
第一个代码段没有. 为什么会这样?据我了解,我应该能够将copy
替换为包含但没有问题的文字数组(就像我在第二个片段中所做的那样).
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.
注意:我知道[...arr]
在这种情况下似乎是多余的,我只是用它来演示我的问题.
Note: I'm aware that [...arr]
seems redundant in this case, I've simply used this to demonstrate my problem.
推荐答案
添加分号,效果很好.
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]
哪个导致了您的错误.
这篇关于为什么我不能在代码中删除中间变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!