简体   繁体   English

任何人都可以在他们的Node.js REPL上使用let语句吗?

[英]Can anyone else use let statements at their Node.js REPL?

Is it possible? 可能吗? It doesn't seem to work in my REPL, neither with nor without --harmony . 它似乎不适用于我的REPL,无论有没有--harmony

What I'd really like to do is use for..of loops, but let seems a simpler thing to troubleshoot and is likely the same reason. 我真正想要做的是使用for..of循环,但是让故障排除似乎更简单,可能是同样的原因。

Anyone know anything about the status of these? 有谁知道这些的状态?

$ node --version
v0.10.13

It was a bit cryptic, you'd think just --harmony would work, but you need to add in a use strict somewhere (which you can do at the command line): 这有点神秘,你只想--harmony会起作用,但你需要在某处添加一个use strict (你可以在命令行中添加):

$ node --harmony --use-strict
> var letTest = function () {
...   let x = 31;
...   if (true) {
.....     let x = 71;  // different variable
.....     console.log(x);  // 71
.....   }
...   console.log(x);  // 31
... }
undefined
> letTest()
71
31
undefined
> 

Much happy! 太开心了!

However, I tried a simple of comprehension and it didn't work: 但是,我尝试了一个简单of理解,它没有用:

[ square(x) for (x of [1,2,3,4,5]) ]

With no luck. 没有运气。 It looks like you may have to go past the current stable release to get all the harmony features. 看起来您可能必须通过当前的稳定版本来获得所有和声功能。

If you run it from a file, node.js will tell you the error : 如果从文件中运行它,node.js会告诉您错误:

SyntaxError: Illegal let declaration outside extended mode

Its details are given in another question What is extended mode? 其详细信息在另一个问题中给出什么是扩展模式? As it happens the extended mode is built on strict mode so you can't use it without "use strict" and harmony flag both. 在发生这种情况时,扩展模式建立在严格模式下,因此如果没有"use strict"和和谐标志,则无法使用它。 The reason I will quote from here : 我将从这里引用的原因:

Recall that ES5 defines "strict mode", a new mode of execution for JS. 回想一下,ES5定义了“严格模式”,这是JS的一种新的执行模式。 Let's call the other mode "classic mode". 我们将其他模式称为“经典模式”。 ES6 defines a third "extended mode", which builds on strict mode, and enables the new features. ES6定义了第三种“扩展模式”,它建立在严格模式之上,并启用了新功能。

The recent node v11.7 has iterators which allow you to use for of loops. 最近的节点v11.7具有允许您for of循环的迭代器。 Example I used : 我用过的例子:

function* fibonacci() {
    let prev = 0, curr = 1, temp;
    for (;;) {
        temp = prev;
        prev = curr;
        curr = temp + curr;
        yield curr;
    }
}

for (let n of fibonacci()) {
    if (n > 1000)
        break;
    console.log(n);
}

For now, I could only use for of over iterators and not simple arrays. 现在,我只能for of迭代器而不是简单的数组。

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

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