运算符 ?= 是什么意思?

What does the operator ?= mean?

我有一个 hamlc(称为 Haml + Inline CoffeeScript),其中有一行

- @variable1 ?= @object1.element[0]

我想知道这是否意味着:如果 @object1.element[0] 有一个值,则将其存储在 @variable1 中。

我找不到任何关于 hamlc 的信息。还有,如果我理解的是对的,如果我想加一个else条件怎么办?

?= 运算符在 CoffeeScript 中称为 existential operator

来自文档:

It's a little difficult to check for the existence of a variable in JavaScript. if (variable) ... comes close, but fails for zero, the empty string, and false. CoffeeScript's existential operator ? returns true unless a variable is null or undefined, which makes it analogous to Ruby's nil?

这意味着它的工作方式是,使用您的示例:

 @variable1 ?= @object1.element[0]

如果 @variable1nullundefined,则将 @object1.element[0] 分配给它。

what if I want to add the condition for "else" ?

@variable1 = 
  if @variable1?
    @object1.element[0]
  else
    # your else clause here