JavaScript箭头语法:右侧的等号是什么意思? [英] JavaScript arrow syntax: What does the equals sign on the right hand side mean?

查看:90
本文介绍了JavaScript箭头语法:右侧的等号是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究JavaScript语法.我偶尔会看到一个使我感到困惑的模式:箭头右手边的等号.例如,如下所示:

I am studying JavaScript syntax. I occasionally see a pattern that confuses me: an equals sign on the right hand side of the arrow. For example, something like this:

.then(data => myVariable = data)

我不知道该语法发生了什么.看起来它正在获取 data 的值并将其分配给名为 myVariable 的变量.有人可以解释吗?

I don't know what is going on in that syntax. It looks like it is taking the value of data and assigning it to the variable named myVariable. Can somebody explain this?

推荐答案

您是对的.这是一个箭头函数(没有附带的框),可返回"赋值表达式-实际上是将 data 的值赋值给 myVariable 并返回右侧,但在这种情况下可能无法使用.

You're right. It's an arrow function (without an accompanying block) that "returns" an assignment expression - in effect doing an assignment of data's value to myVariable and returning the right hand side, though that might not be utilized in this case.

在更简化的情况下:

let foo = 3;
function foobar(callback) {
  const result = callback(5); //call callback with 5 as argument
  console.log(result); //5
}
foobar(five => foo = five); //assigns 5 to foo
console.log(foo); //5

这通常不是最易读的选项,您的问题证明了这一点.我建议像这样添加一个块(如果您不打算实际返回右侧值):

This is generally not the most readable option and your question proves this. I would recommend adding a block like so (if you don't intend on actually returning the right hand side value):

myPromise.then(data => {
  myVariable = data;
});

在这种情况下,赋值表达式的右侧没有隐式返回,并且使意图更清晰.同样,不鼓励您进行分配,例如您按照我对异步承诺的假设所做的正确的事情.

In which case there is no implicit return of the assignment expression's right hand side and makes the intent clearer. Also, assignments such as what you're doing right with what I assume to an asynchronous promise are not encouraged.

也许会使用异步/等待或其他新的ES功能来处理异步代码,而不是使用可能会在

Maybe look into async/await or other new ES features to deal with asynchronous code other than using variable assignments which may run into some problems if not used correctly.

这篇关于JavaScript箭头语法:右侧的等号是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆