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

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

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

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

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

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


当前回答

现在,它在Chrome、Edge、Firefox、Safari等主流浏览器的最新版本中得到了完全支持。下面是空运算符和空合并运算符的比较

const response = {
        settings: {
            nullValue: null,
            height: 400,
            animationDuration: 0,
            headerText: '',
            showSplashScreen: false
        }
    };
    /* OR Operator */
    const undefinedValue = response.settings.undefinedValue || 'Default Value'; // 'Default Value'
    const nullValue = response.settings.nullValue || 'Default Value'; // 'Default Value'
    const headerText = response.settings.headerText || 'Hello, world!'; //  'Hello, world!'
    const animationDuration = response.settings.animationDuration || 300; //  300
    const showSplashScreen = response.settings.showSplashScreen || true; //  true
    /* Nullish Coalescing Operator */
    const undefinedValue = response.settings.undefinedValue ?? 'Default Value'; // 'Default Value'
    const nullValue = response.settings.nullValue ?? ''Default Value'; // 'Default Value'
    const headerText = response.settings.headerText ?? 'Hello, world!'; // ''
    const animationDuration = response.settings.animationDuration ?? 300; // 0
    const showSplashScreen = response.settings.showSplashScreen ?? true; //  false

其他回答

ECMAScript 2021启用了两个新功能:

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

设b=未定义??5.console.log(b);//5.

逻辑零赋值(x??=y)运算符,仅在x具有零值(空或未定义)时赋值。

常量车={速度:20};车速??=5.控制台日志(轿厢速度);汽车名称??=“雷诺”;console.log(car.name);

有关逻辑零赋值的更多信息,请参阅此处https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_nullish_assignment

有关空合并运算符的更多信息,请参阅此处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开始,该功能现在也可用。

请注意null的JavaScript特定定义。javascript中“无值”有两个定义。1.空:当变量为空时,表示该变量中不包含数据,但该变量已在代码中定义。这样地:

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

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

window.alert(typeof myEmptyValue); // prints Object

未定义:当一个变量之前没有在代码中定义,并且正如预期的那样,它不包含任何值。这样地:如果(myUndefinedValue==undefined){window.alert('it is undefined');}//警报

如果是这种情况,则变量的类型为“undefined”。

注意,如果您使用类型转换比较运算符(==),JavaScript将对这两个空值起同等作用。要区分它们,请始终使用类型严格比较运算符(==)。

现在,它在Chrome、Edge、Firefox、Safari等主流浏览器的最新版本中得到了完全支持。下面是空运算符和空合并运算符的比较

const response = {
        settings: {
            nullValue: null,
            height: 400,
            animationDuration: 0,
            headerText: '',
            showSplashScreen: false
        }
    };
    /* OR Operator */
    const undefinedValue = response.settings.undefinedValue || 'Default Value'; // 'Default Value'
    const nullValue = response.settings.nullValue || 'Default Value'; // 'Default Value'
    const headerText = response.settings.headerText || 'Hello, world!'; //  'Hello, world!'
    const animationDuration = response.settings.animationDuration || 300; //  300
    const showSplashScreen = response.settings.showSplashScreen || true; //  true
    /* Nullish Coalescing Operator */
    const undefinedValue = response.settings.undefinedValue ?? 'Default Value'; // 'Default Value'
    const nullValue = response.settings.nullValue ?? ''Default Value'; // 'Default Value'
    const headerText = response.settings.headerText ?? 'Hello, world!'; // ''
    const animationDuration = response.settings.animationDuration ?? 300; // 0
    const showSplashScreen = response.settings.showSplashScreen ?? true; //  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背景,这将是最自然的感觉解决方案。