且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

是否存在“空合并"?JavaScript 中的运算符?

更新时间:2022-06-14 23:14:56

更新

JavaScript 现在支持 空合并运算符 (??).当其左侧操作数为 nullundefined 时,它返回其右侧操作数,否则返回其左侧操作数.

JavaScript now supports the nullish coalescing operator (??). It returns its right-hand-side operand when its left-hand-side operand is null or undefined, and otherwise returns its left-hand-side operand.

请在使用前检查兼容性.

Please check compatibility before using it.

与 C# 空合并运算符 (??) 等效的 JavaScript 使用逻辑 OR (||):

The JavaScript equivalent of the C# null coalescing operator (??) is using a logical OR (||):

var whatIWant = someString || "Cookies!";

在某些情况下(在下面澄清),行为与 C# 的行为不匹配,但这是在 JavaScript 中分配默认值/替代值的通用、简洁的方式.

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.

无论第一个操作数的类型如何,如果将其转换为布尔值导致 false,则赋值将使用第二个操作数.请注意以下所有情况:

Regardless of the type of the first operand, if casting it to a Boolean results in false, the assignment will use the second operand. 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! :)

这意味着:

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"