简体   繁体   English

为什么我不能删除代码中的中间变量?

[英]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); }); 

However, if I remove the intermediate variable copy , my code seems to throw an error: 但是,如果我删除中间变量copy ,我的代码似乎抛出一个错误:

 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 ... 未捕获的SyntaxError:意外的令牌......

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). 根据我的理解,我应该能够用它包含的文字数组替换copy并且没有问题(正如我在第二个片段中所做的那样)。

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. 注意 :我知道[...arr]在这种情况下似乎是多余的,我只是用它来证明我的问题。

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. 这导致了你的错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM