I don't get why
我不明白为什么
(var ||= []) << 1
works as expected but
工作如预期但
(var ||= true) = false
doesn't.
不喜欢。
Could anyone explain why it doesnt work and what is going on here?
谁能解释一下为什么它不管用,这是怎么回事吗?
2 个解决方案
#1
12
a ||= b
behaves like a || a = b
.
||= b表现为|| a = b。
An assignment returns the assigned value, i.e., var = true
returns true
.
赋值返回赋值,即。,var = true返回true。
var ||= true
will evaluate to the assignment var = true
, because var
is undefined at that point. If var
is defined and its value is true
, it will return the value of var
, that is true
; if it's false, it will return the value of true
, which is true
.
var ||= true将评估赋值var = true,因为var在那个点没有定义。如果定义了var且其值为true,则返回var的值为true;如果它是假的,它会返回true的值,这是真的。
var ||= []
returns []
, and your first expression evaluated to [] << 1
, which is legal.
var ||=[]返回[],第一个表达式计算为[]< 1,这是合法的。
However, your second expression evaluates to true = false
, which throws a compile error.
但是,第二个表达式的计算值为true = false,这会抛出一个编译错误。
tl;dr
博士tl;
(var ||= []) << 1
⟺ (var = []) << 1
⟺ [] << 1
✔
(var | | =[])< < 1⟺(var =[])< < 1⟺✔[]< < 1
(var ||= true) = false
⟺ (var = true) = false
⟺ true = false
✘
(var | | = true)= false⟺(var = true)= = false✘假⟺如此
#2
3
In the first case you have an object, and you uses its <<
method.
在第一种情况下,您有一个对象,并使用它的 <方法。< p>
In the second case you have an assignment, where the right expression must be assigned to a variable on the left, not to an object or expression.
在第二种情况下,您有一个赋值,其中右表达式必须分配给左边的变量,而不是对象或表达式。
#1
12
a ||= b
behaves like a || a = b
.
||= b表现为|| a = b。
An assignment returns the assigned value, i.e., var = true
returns true
.
赋值返回赋值,即。,var = true返回true。
var ||= true
will evaluate to the assignment var = true
, because var
is undefined at that point. If var
is defined and its value is true
, it will return the value of var
, that is true
; if it's false, it will return the value of true
, which is true
.
var ||= true将评估赋值var = true,因为var在那个点没有定义。如果定义了var且其值为true,则返回var的值为true;如果它是假的,它会返回true的值,这是真的。
var ||= []
returns []
, and your first expression evaluated to [] << 1
, which is legal.
var ||=[]返回[],第一个表达式计算为[]< 1,这是合法的。
However, your second expression evaluates to true = false
, which throws a compile error.
但是,第二个表达式的计算值为true = false,这会抛出一个编译错误。
tl;dr
博士tl;
(var ||= []) << 1
⟺ (var = []) << 1
⟺ [] << 1
✔
(var | | =[])< < 1⟺(var =[])< < 1⟺✔[]< < 1
(var ||= true) = false
⟺ (var = true) = false
⟺ true = false
✘
(var | | = true)= false⟺(var = true)= = false✘假⟺如此
#2
3
In the first case you have an object, and you uses its <<
method.
在第一种情况下,您有一个对象,并使用它的 <方法。< p>
In the second case you have an assignment, where the right expression must be assigned to a variable on the left, not to an object or expression.
在第二种情况下,您有一个赋值,其中右表达式必须分配给左边的变量,而不是对象或表达式。