首页 文章

JavaScript中是否有“null coalescing”运算符?

提问于
浏览
1042

Javascript中是否存在空合并运算符?

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

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

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

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

这有点ick嘿恕我直言 . 我可以做得更好吗?

8 回答

  • 13

    如果 || 替换为C#的 ?? 在你的情况下还不够好,因为它吞下空字符串和零,你总是可以编写自己的函数:

    function $N(value, ifnull) {
        if (value === null || value === undefined)
          return ifnull;
        return value;
     }
    
     var whatIWant = $N(someString, 'Cookies!');
    
  • 3

    目前没有支持,但JS标准化流程正在努力:https://github.com/tc39/proposal-optional-chaining

  • 10
    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 coalesce函数,它接受任意数量的参数,如果它们都没有值,则返回null . 它的行为就像C#??运算符,“”,false和0被认为是NOT NULL,因此计为实际值 . 如果你来自.net背景,这将是最自然的感觉解决方案 .

  • 60

    是的,它即将推出 . 见proposal hereimplementation status here .

    它看起来像这样:

    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
    
  • 1678

    在这里没有人提到 NaN 的潜力,对我而言,这也是一个零值 . 所以,我以为我会增加两美分 .

    对于给定的代码:

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

    如果您使用 || 运算符,则会获得第一个非假值:

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

    如果您使用典型的合并方法as posted here,您将获得 c ,其值为: NaN

    var result = coalesce(a,b,c,d,e,f); // result.toString() === 'NaN'
    

    Neither 这些似乎对我而言 . 在我自己的小合并逻辑世界中,可能与你的世界不同,我认为undefined,null和NaN都是"null-ish" . 所以,我希望从coalesce方法中获得 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的事实 . 你可以在这里阅读更多内容:Why is NaN not equal to 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;
    }
    
  • 39

    要小心null的JavaScript特定定义 . javascript中有“无 Value ”的两个定义 . 1. Null:当变量为null时,表示其中不包含任何数据,但该变量已在代码中定义 . 像这样:

    var myEmptyValue = 1;
    myEmptyValue = null;
    if ( myEmptyValue === null ) { window.alert('it is null'); }
    // alerts
    

    在这种情况下,变量的类型实际上是Object . 测试一下 .

    window.alert(typeof myEmptyValue); // prints Object
    
    • 未定义:如果之前未在代码中定义变量,并且按预期方式,则不包含任何值 . 像这样:
    if ( myUndefinedValue === undefined ) { window.alert('it is undefined'); }
    // alerts
    

    如果是这种情况,变量的类型是'undefined' .

    请注意,如果使用类型转换比较运算符(==),JavaScript将同时对这两个空值起作用 . 为了区分它们,总是使用type-strict比较运算符(===) .

  • 6

    在阅读完澄清后,@ Ates Goral的回答提供了如何在JavaScript中执行与C#相同的操作 .

    @Gumbo 's answer provides the best way to check for null; however, it'重要的是要注意JavaScript中 ===== 的区别,特别是在检查 undefined 和/或 null 时 .

    关于两个术语here之间的区别,有一篇非常好的文章 . 基本上,要理解如果使用 == 而不是 === ,JavaScript将尝试合并您正在比较的值,并返回此合并后的比较结果 .

  • 4

    C#null合并运算符( ?? )的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"
    

相关问题