简体   繁体   English

Node.Js 中有海象运算符吗?

[英]Is there a walrus operator in Node.Js?

In Python3.8 There is new operator called walrus which can assign new variables inside a condition.Python3.8 中有一个名为walrus的新运算符,它可以在条件内分配新变量。 Is there something similar to it in Node.Js ? Node.Js中是否有类似的东西?

my_var = 5
if (result := my_var == 5):
    print(result)

There's no need for a separate operator, assignment is already an expression in Javascript:不需要单独的运算符,赋值已经是 Javascript 中的表达式:

"use strict";
var my_var = 5;
var result;
if (result = my_var == 5){
  console.log(result)
}

Assign and compare as one expression.分配和比较作为一个表达式。 To make it work in strict mode and avoid linter complaints, add parentheses to the assignment.要使其在严格模式下工作并避免 linter 投诉,请在作业中添加括号。

const my_var = 5;
let result;
if ((result = my_var) === 5) {
  console.log(result);
}

https://eslint.org/docs/rules/no-cond-assign#except-parens https://eslint.org/docs/rules/no-cond-assign#except-parens

You can do it like this:你可以这样做:

const myNumber = 2;
let newNumber;

if (newNumber = myNumber === 2) {
  console.log('this works!');
}

It's kind of the same, it has an assignment and a comparison in the same line.它有点相同,它在同一行中有一个赋值和一个比较。 You can obviously substitute your problem with this:你显然可以用这个代替你的问题:

const my_var = 5;
let result;
if(result = my_var === 5) {
 console.log(result);
}

As you can see it's obligatory to have a let declaration before-hand.如您所见,必须事先声明一个 let 。

This can't work unless you're not using strict mode.除非您不使用严格模式,否则这是行不通的。 It's to prevent mistakes.是为了防止出错。

You can see this part of the document on MDN for more info 您可以在 MDN 上查看文档的这一部分以获取更多信息

You can do what @juanpa.arrivillaga mentioned if you don't use strict mode, which I strongly advise again.如果您不使用严格模式,您可以执行@juanpa.arrivillaga 提到的操作,我再次强烈建议您这样做。 Strict mode will save you 100x more headache than it will make you.严格模式将为您节省 100 倍的头痛。

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

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