Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
438 views
in Technique[技术] by (71.8m points)

javascript - JavaScript中是否有“空合并”运算符?(Is there a “null coalescing” operator in JavaScript?)

Is there a null coalescing operator in Javascript?

(Javascript中是否有空合并运算符?)

For example, in C#, I can do this:

(例如,在C#中,我可以这样做:)

String someString = null;
var whatIWant = someString ?? "Cookies!";

The best approximation I can figure out for Javascript is using the conditional operator:

(我可以为Javascript找到的最佳近似是使用条件运算符:)

var someString = null;
var whatIWant = someString ? someString : 'Cookies!';

Which is sorta icky IMHO.

(恕我直言,这有点棘手。)

Can I do better?

(我可以做得更好吗?)

  ask by Daniel Schaffer translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...