var myvar1 = myvar2 = myvar3 的结果是什么?
我在一些 Nodejs 脚本中看到像这样使用变量/对象:
var myvar1 = myvar2 = myvar3;
为什么使用这个以及它意味着什么?
I have seen in some nodejs scripts variables/objects being used like this:
var myvar1 = myvar2 = myvar3;
Why is this used and what does it mean?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
它将
首先将
myvar3
分配给myvar2
(没有var
,因此可能是隐式全局的,请注意)。然后它将把
myvar3
的值赋给myvar1
,因为设置值被返回。结果再次返回,不会做任何进一步的事情 - 在最后一行中,
myvar3
的值没有任何反应。所以最终它们都具有相同的价值。
It will evaluate to:
It will first assign
myvar3
tomyvar2
(withoutvar
, so possibly implicit global, watch out for that).Then it will assign
myvar3
's value tomyvar1
, because the set value is returned.The result is again returned, which won't do anything further - in the final line nothing happens with
myvar3
's value.So in the end they have all the same value.
这会将
myvar2
设置为myvar3
,并将myvar1
设置为myvar2
。我假设
myvar3
和myvar2
已在此行之前声明。如果没有,myvar2
将是全局变量(因为没有var
),如果myvar3
未定义,则会出现错误。这扩展到:
This sets
myvar2
tomyvar3
, and setsmyvar1
tomyvar2
.I assume
myvar3
andmyvar2
have been declared before this line. If not,myvar2
would be a global (as there's novar
), and ifmyvar3
wasn't defined, this would give an error.This expands to:
如果:
那么它们都是
= 5
If:
Then they are all
= 5
myvar1 和 myvar2 都获得 myvar3 的名称。
第一个要计算的表达式是 myvar2 = myvar3。这会将 myvar3 分配给 myvar2。此操作的结果是分配的 value ,然后将其分配给 myvar1。
myvar1 and myvar2 both get the name of myvar3.
the first expression to evaluate is myvar2 = myvar3. This assigns myvar3 to myvar2. The result of this operation is the assigned value , and this is then assigned to myvar1.
这会将变量 myvar1 和 myvar2 分配给 myvar3 的值。我不知道他们为什么这样做,但我最好的猜测是他们希望这两个变量与 myvar3 具有相同的值。
This will assign the variables myvar1 and myvar2 to the value of myvar3. Why they do this is unknown to me, but my best guess is they want the two vars to be the same value of myvar3.
正如已经解释过的,该语句导致所有变量的值为
myvar3
。我想补充一点:使用这样的语句,您必须注意范围,通过以下方式证明:
并分配非原始值(因此,对对象的引用)
as already explained, the statement results in all variables having the value
myvar3
.I like to add: using statements like that you have to beware of scope, demonstrated by:
And of assigning non primitive values (so, references to objects)