<分区>
如果新值未定义,这是更新变量并保留原始值的合法方法吗?
variable = NEWVAR || variable;
我创建了一个 Fiddle到目前为止它看起来不错,但我不想遇到任何令人讨厌的惊喜。
这是一个测试用例:
var test = "hello";
test = undefined || test;
alert('"' + test + '"');
<分区>
如果新值未定义,这是更新变量并保留原始值的合法方法吗?
variable = NEWVAR || variable;
我创建了一个 Fiddle到目前为止它看起来不错,但我不想遇到任何令人讨厌的惊喜。
这是一个测试用例:
var test = "hello";
test = undefined || test;
alert('"' + test + '"');
最佳答案
我会说,是的,我经常使用它。但你必须记住这一点
Douglas Crockford:Javascript 的优点(第 40 页)
The || operator produces the value of its first operand if the first operand is truthy. Otherwise, it produces the value of the second operand.
因此,如果 NEWVAR
包含任何虚假值 (false
,null
,undefined
,NaN
,0
,""
) 值,计算第二个操作数。
只要您知道这一点,您就可以随时使用 ||
运算符来获取默认值
Douglas Crockford:Javascript 的优点(第 51 页)
The || operator can be used to fill in default values:
var middle = stooge["middle-name"] || "(none)";
var status = flight.status || "unknown";
关于javascript - 保留原始值 "variable = NEWVAR || variable;",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15362703/