The JavaScript equivalent of the C# null coalescing operator ( ??
) is using a logical OR ( ||
):
(与C#空合并运算符( ??
)等效的JavaScript使用逻辑OR( ||
):)
var whatIWant = someString || "Cookies!";
There are cases (clarified below) that the behaviour won't match that of C#, but this is the general, terse way of assigning default/alternative values in JavaScript.
(在某些情况下(如下所述),该行为与C#的行为不匹配,但这是在JavaScript中分配默认/替代值的通用,简洁的方法。)
Clarification (澄清度)
Regardless of the type of the first operand, if casting it to a Boolean results in false
, the assignment will use the second operand.
(无论第一个操作数的类型如何,如果将其强制转换为Boolean都将导致false
,则赋值将使用第二个操作数。)
Beware of all the cases below: (当心以下所有情况:)
alert(Boolean(null)); // false
alert(Boolean(undefined)); // false
alert(Boolean(0)); // false
alert(Boolean("")); // false
alert(Boolean("false")); // true -- gotcha! :)
This means:
(这意味着:)
var whatIWant = null || new ShinyObject(); // is a new shiny object
var whatIWant = undefined || "well defined"; // is "well defined"
var whatIWant = 0 || 42; // is 42
var whatIWant = "" || "a million bucks"; // is "a million bucks"
var whatIWant = "false" || "no way"; // is "false"
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…