简体   繁体   English

JavaScript 中的海象运算符等效项

[英]Walrus operator equivalent in JavaScript

Is there an equivalent of Python's walrus operator ':=' in JavaScript?在 JavaScript 中是否有相当于 Python 的海象运算符“:=”? I know it's possible to do:我知道可以这样做:

for (let i = 0; (result = foo(i)) < N; i++) {
    // Do stuff.
}

but I want result to be constrained to the scope of the for-loop.但我希望将result限制在 for 循环的 scope 上。

You could declare result inside of the for 's scope.您可以在for的 scope 中声明result

for (let i = 0, result; (result = foo(i)) < N; i++) {
    // Do stuff.
}

Just as an alternative to Nina's good approach : Any time you want to have a variable in a narrower scope than its surroundings, you can also use a freestanding block:就像Nina 的好方法的替代方法一样:任何时候你想在比周围环境更窄的 scope 中拥有一个变量,你也可以使用一个独立的块:

{
    let result;
    // ...
}

That would free you from using for without an increment expression (I'm of the school that all three parts of a for should be used, or use a different loop):这将使您无需使用增量表达式就可以使用for (我所在的学校应该使用for的所有三个部分,或者使用不同的循环):

{
    let i = 0, result;
    while ((result = foo(i++)) < N) {
        // Do stuff...
    }
}

Live Example:现场示例:

 const foo = x => x; const N = 5; { let i = 0, result; while ((result = foo(i++)) < N) { // Do stuff... console.log(result); } }

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

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