Javascript或赋值运算符

4

我在查看一些编译过的coffee-script代码时,发现了以下内容,我觉得非常奇怪:

var current, x = 8;
current = this._head || (this._head = x);

运行后,当前值为8。从逻辑运算符||的工作方式来看,我原本希望它先计算左侧。在左侧得到“未定义”之后,它会转而计算右侧,将this._head赋值为8。然后返回true,但这部分不是很重要吗?我不知道它如何会返回并影响“current”变量?任何帮助都将不胜感激,谢谢!

哦!我刚意识到我被操作符优先级卡住了。在任何值被赋给current之前,||操作符就已经执行了。我本质上是想象current = this._head周围有括号。谢谢大家! - elju
3个回答

1

|| 运算符返回的是 ,而不是 true。也许这样说会更有帮助。

current = this._head || (this._head = x)

也可以写成

current = this._head ? this._head : (this._head = x);

或者

current = this._head;

if(!current)
    current = this._head = x;

1
  1. || 运算符如果左侧为“真值”,则返回左侧,否则返回右侧 -- 不管其真假性。它不会将表达式强制转换为布尔值 true/false!
    • undefined || (this._head = x) 返回右侧
  2. 赋值运算符也会返回一个值!
    • 在上面的例子中,this._head = x 返回 8
  3. 第一个赋值运算符将值 8 赋给变量 current

0

你可以使用表达式

var current=this._head ? this._head : (this._head = x);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接