JavaScript中是否有“空合并”运算符?

JavaScript

Pro路易

2020-03-09

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

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

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

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

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

这有点怪异恕我直言。我可以做得更好吗?

第273篇《JavaScript中是否有“空合并”运算符?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

6个回答
阿飞小卤蛋 2020.03.09

确定正确的答案

它是否存在于JavaScript中? 是的,它确实。 但。当前处于阶段32020-02-06,目前尚未在任何地方获得支持。单击下面URL中的链接,然后转到“规格”和“浏览器兼容性”标题,以获取有关其位置的更多信息。

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

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

与逻辑OR(||)运算符相反,如果左操作数是一个不为null或未定义的虚假值,则将其返回。换句话说,如果您使用|| 为了为另一个变量foo提供一些默认值,如果您认为某些虚假的值可用(例如''或0),则可能会遇到意外行为。请参阅下面的更多示例。

想要例子吗?跟随我发布的链接,它包含了所有内容。

TomGil村村 2020.03.09

For people using Typescript, you can use the nullish coalescing operator from Typescript 3.7

From the docs -

You can think of this feature - the ?? operator - as a way to “fall back” to a default value when dealing with null or undefined. When we write code like

let x = foo ?? bar();

这是一种新的表示值foo“存在”时将被使用的方式;但是当它是null或时undefined,请计算bar()其位置。

村村AL 2020.03.09

阅读您的说明后,@ Ates Goral的答案提供了如何执行与JavaScript中C#相同的操作。

@Gumbo的答案提供了检查null的最佳方法;但是,重要的是要注意JavaScript =====JavaScript之间的区别,尤其是在涉及检查undefined和/或问题时null

有关于两个词的区别一个真正的好文章在这里基本上,请理解,如果您使用==而不是===,JavaScript将尝试合并您正在比较的值,并合并返回比较的结果

TomMandy 2020.03.09

目前尚不支持,但是JS标准化过程正在其上进行:https : //github.com/tc39/proposal-optional-chaining

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

菏以飘落 2020.03.09

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

var whatIWant = someString || "Cookies!";

在某些情况下(以下已说明),该行为与C#的行为不匹配,但这是在JavaScript中分配默认/替代值的通用,简洁的方法。


澄清度

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! :)

This means:

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"

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android