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背景,这将是最自然的感觉解决方案。

这里没有人提到NaN的潜力,对我来说,它也是一个空值。所以,我想再加上两美分。

对于给定代码:

var a,
    b = null,
    c = parseInt('Not a number'),
    d = 0,
    e = '',
    f = 1
;

如果要使用||运算符,将获得第一个非false值:

var result = a || b || c || d || e || f; // result === 1

如果你使用新的??(空合并)运算符,将得到c,其值为:NaN

vas result = a ?? b ?? c ?? d ?? e ?? f; // result === NaN

我觉得这两个都不对。在我自己的联合逻辑小世界里,我认为未定义的、空的和NaN都是“空的”。所以,我希望从联合方法中得到d(零)。

如果任何人的大脑都像我一样工作,并且你想排除NaN,那么这个定制的联合方法(与这里发布的方法不同)将实现这一点:

function coalesce() {
    var i, undefined, arg;

    for( i=0; i < arguments.length; i++ ) {
        arg = arguments[i];
        if( arg !== null && arg !== undefined
            && (typeof arg !== 'number' || arg.toString() !== 'NaN') ) {
            return arg;
        }
    }
    return null;
}

对于那些希望代码尽可能简短,并且不介意有点不够清晰的人,您也可以按照@impinball的建议使用此选项。这利用了NaN永远不等于NaN的事实。你可以在这里读到更多:为什么NaN不等于NaN?

function coalesce() {
    var i, arg;

    for( i=0; i < arguments.length; i++ ) {
        arg = arguments[i];
        if( arg != null && arg === arg ) { //arg === arg is false for NaN
            return arg;
        }
    }
    return null;
}

是的,它的建议现在是第四阶段。这意味着该提案已准备好纳入正式的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中提供,因为截至2020年4月,它处于提案阶段。您可以在此处监视状态以获得兼容性和支持-https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator

对于使用Typescript的用户,您可以使用Typescript 3.7中的零合并运算符

从文档中-

你可以想到这个功能-??操作员-作为“跌倒”的方式当处理null或undefined时,返回到默认值。当我们编写类似代码让x=foo??bar();这是一种新的说法,即当foo值为“present”时将使用它;但当它为空或未定义时,在其位置计算bar()。

需要支持旧浏览器并具有对象层次结构

body.head.eyes[0]  //body, head, eyes  may be null 

可以使用此,

(((body||{}) .head||{}) .eyes||[])[0] ||'left eye'