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

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

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

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

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

这有点讨厌IMHO。我能做得更好吗?


当前回答

是的,它很快就要来了。请参阅此处的提案和此处的实施状态。

它看起来像这样:

x ?? y

实例

const response = {
  settings: {
    nullValue: null,
    height: 400,
    animationDuration: 0,
    headerText: '',
    showSplashScreen: false
  }
};

const undefinedValue = response.settings?.undefinedValue ?? 'some other default'; // result: 'some other default'
const nullValue = response.settings?.nullValue ?? 'some other default'; // result: 'some other default'
const headerText = response.settings?.headerText ?? 'Hello, world!'; // result: ''
const animationDuration = response.settings?.animationDuration ?? 300; // result: 0
const showSplashScreen = response.settings?.showSplashScreen ?? true; // result: false

其他回答

function coalesce() {
    var len = arguments.length;
    for (var i=0; i<len; i++) {
        if (arguments[i] !== null && arguments[i] !== undefined) {
            return arguments[i];
        }
    }
    return null;
}

var xyz = {};
xyz.val = coalesce(null, undefined, xyz.val, 5);

// xyz.val now contains 5

此解决方案与SQL联合函数类似,它接受任意数量的参数,如果它们都没有值,则返回null。它的行为类似于C#??运算符,即“”、false和0被视为NOT NULL,因此算作实际值。如果你来自.net背景,这将是最自然的感觉解决方案。

是的,它很快就要来了。请参阅此处的提案和此处的实施状态。

它看起来像这样:

x ?? y

实例

const response = {
  settings: {
    nullValue: null,
    height: 400,
    animationDuration: 0,
    headerText: '',
    showSplashScreen: false
  }
};

const undefinedValue = response.settings?.undefinedValue ?? 'some other default'; // result: 'some other default'
const nullValue = response.settings?.nullValue ?? 'some other default'; // result: 'some other default'
const headerText = response.settings?.headerText ?? 'Hello, world!'; // result: ''
const animationDuration = response.settings?.animationDuration ?? 300; // result: 0
const showSplashScreen = response.settings?.showSplashScreen ?? true; // result: false

这里有两项:

逻辑或

const foo=“”|“默认字符串”;

console.log(foo);//输出为“默认字符串”

空合并运算符

常量foo=''??'默认字符串';

console.log(foo);//输出为空字符串,即“”

零合并运算符(??)是一种逻辑运算符,当左侧操作数为空或未定义时,它返回右侧操作数,否则返回左侧操作数。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator

是的,它的建议现在是第四阶段。这意味着该提案已准备好纳入正式的ECMAScript标准。您已经可以在Chrome、Edge和Firefox的最新桌面版本中使用它,但我们需要等待一段时间,直到该功能达到跨浏览器的稳定性。

查看以下示例以演示其行为:

//注意:只有在运行上述浏览器的最新版本时,这才有效const var1=未定义;const var2=“回退值”;常量结果=var1??var2;console.log(`${result}`中的空合并结果);

上一示例等效于:

const var1=未定义;const var2=“回退值”;常量结果=(var1!==null&&var1!===undefined)?变量1:var2;console.log(`${result}`中的空合并结果);

请注意,无效合并不会像||运算符那样威胁虚假值(它只检查未定义的值或空值),因此下面的代码片段将如下所示:

//注意:只有在运行上述浏览器的最新版本时,这才有效常量var1=“”;//空字符串const var2=“回退值”;常量结果=var1??var2;console.log(`${result}`中的空合并结果);


对于TypesScript用户,从TypeScript 3.7开始,该功能现在也可用。

使现代化

JavaScript现在支持空值合并运算符(??)。当左侧操作数为空或未定义时,它返回右侧操作数,否则返回左侧操作数。

旧答案

使用前请检查兼容性。


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

var whatIWant = someString || "Cookies!";

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


澄清

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

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"