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

其他回答

这里没有人提到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;
}

请注意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将对这两个空值起同等作用。要区分它们,请始终使用类型严格比较运算符(==)。

这里有两项:

逻辑或

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

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

空合并运算符

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

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

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

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

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

@Gumbo的答案提供了检查空值的最佳方法;然而,注意JavaScript中==与==的区别很重要,特别是在检查未定义和/或null时。

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

逻辑零赋值,2020+解决方案

当前正在向浏览器中添加新的运算符??=。这将组合空合并运算符??赋值运算符=。

注意:这在公共浏览器版本中尚不常见。将随可用性更改而更新。

??= 检查变量是否未定义或为空,如果已定义则短路。如果没有,则将右侧值分配给变量。

基本示例

let a          // undefined
let b = null
let c = false

a ??= true  // true
b ??= true  // true
c ??= true  // false

对象/阵列示例

let x = ["foo"]
let y = { foo: "fizz" }

x[0] ??= "bar"  // "foo"
x[1] ??= "bar"  // "bar"

y.foo ??= "buzz"  // "fizz"
y.bar ??= "buzz"  // "buzz"

x  // Array [ "foo", "bar" ]
y  // Object { foo: "fizz", bar: "buzz" }

浏览器支持1月22日-89%

Mozilla文档