是否存在“空合并”? JavaScript 中的运算符?

发布于 2024-07-12 14:03:36 字数 327 浏览 10 评论 0原文

JavaScript 中有空合并运算符吗?

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

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

我能想到的 Javascript 的最佳近似是使用条件运算符:

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

恕我直言,这有点令人讨厌。 我可以做得更好吗?

Is there a null coalescing operator in Javascript?

For example, in C#, I can do this:

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

The best approximation I can figure out for Javascript is using the conditional operator:

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

Which is sorta icky IMHO. Can I do better?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(19

原来是傀儡 2024-07-19 14:03:37

更新

JavaScript 现在支持 nullish合并运算符 (??)。 当其左侧操作数为 nullundefined 时,它返回其右侧操作数,否则返回其左侧操作数。

旧答案

使用前请检查兼容性。


JavaScript 中 C# 空合并运算符 (??) 的等效项是使用逻辑 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"

Update

JavaScript now supports the nullish coalescing operator (??). It returns its right-hand-side operand when its left-hand-side operand is null or undefined, and otherwise returns its left-hand-side operand.

Old Answer

Please check compatibility before using it.


The JavaScript equivalent of the C# null coalescing operator (??) is using a logical OR (||):

var whatIWant = someString || "Cookies!";

There are cases (clarified below) that the behaviour won't match that of C#, but this is the general, terse way of assigning default/alternative values in JavaScript.


Clarification

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"
肥爪爪 2024-07-19 14:03:37
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 背景,这将是最自然的感觉解决方案。

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

this solution works like the SQL coalesce function, it accepts any number of arguments, and returns null if none of them have a value. It behaves like the C# ?? operator in the sense that "", false, and 0 are considered NOT NULL and therefore count as actual values. If you come from a .net background, this will be the most natural feeling solution.

苍景流年 2024-07-19 14:03:37

是的,它即将到来。 请参阅此处的提案此处的实施状态

它看起来像这样:

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

Yes, it is coming soon. See proposal here and implementation status here.

It looks like this:

x ?? y

Example

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
走野 2024-07-19 14:03:37

如果 || 作为 C# 的 ?? 的替代品在您的情况下不够好,因为它会吞下空字符串和零,您始终可以编写自己的函数:

 function $N(value, ifnull) {
    if (value === null || value === undefined)
      return ifnull;
    return value;
 }

 var whatIWant = $N(someString, 'Cookies!');

If || as a replacement of C#'s ?? isn't good enough in your case, because it swallows empty strings and zeros, you can always write your own function:

 function $N(value, ifnull) {
    if (value === null || value === undefined)
      return ifnull;
    return value;
 }

 var whatIWant = $N(someString, 'Cookies!');
只为一人 2024-07-19 14:03:37

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

这两个对我来说都不合适。 在我自己的合并逻辑小世界中(可能与您的世界不同),我认为 undefined、null 和 NaN 都是“null-ish”。 因此,我希望从合并方法中返回 d(零)。

如果有人的大脑像我一样工作,并且您想排除 NaN,那么这个自定义 coalesce 方法(与 这里发布的)将实现这一点:

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?< /a>

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;
}

Nobody has mentioned in here the potential for NaN, which--to me--is also a null-ish value. So, I thought I'd add my two-cents.

For the given code:

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

If you were to use the || operator, you get the first non-false value:

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

If you use the new ?? (null coalescing) operator, you will get c, which has the value: NaN

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

Neither of these seem right to me. In my own little world of coalesce logic, which may differ from your world, I consider undefined, null, and NaN as all being "null-ish". So, I would expect to get back d (zero) from the coalesce method.

If anyone's brain works like mine, and you want to exclude NaN, then this custom coalesce method (unlike the one posted here) will accomplish that:

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;
}

For those who want the code as short as possible, and don't mind a little lack of clarity, you can also use this as suggested by @impinball. This takes advantage of the fact that NaN is never equal to NaN. You can read up more on that here: 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;
}
不忘初心 2024-07-19 14:03:37

?? vs || vs &&

其他答案都没有比较所有这三个。 由于贾斯汀·约翰逊的评论有这么多票,并且因为 双问号 vs && 在 javascript 中被标记为与此重复,因此在答案中包含 && 是有意义的。

首先,受 Justin Johnson 评论的启发:

  • || 返回第一个“truey”值,否则返回最后一个值。

  • && 返回第一个“falsey”值,否则返回最后一个值。

  • ?? 返回第一个非空、非未定义的值,否则返回最后一个值,无论它是什么。

然后,用实时代码演示:

let F1,
    F2 = null,
    F3 = 0,
    F4 = '',
    F5 = parseInt('Not a number (NaN)'),
    T1 = 3,
    T2 = 8

console.log( F1 || F2 || F3 || F4 || F5 || T1 || T2 ) // 3 (T1)
console.log( F1 || F2 || F3 || F4 || F5 )             // NaN (F5)

console.log( T1 && T2 && F1 && F2 && F3 && F4 && F5 ) // undefined (F1)
console.log( T1 && T2 )                               // 8 (T2)

console.log( F1 ?? F2 ?? F3 ?? F4 ?? F5 ?? T1 )       // 0 (F3)
console.log( F1 ?? F2)                                // null (F2)

?? vs || vs &&

None of the other answers compares all three of these. Since Justin Johnson's comment has so many votes, and since double question mark vs && in javascript was marked a duplicate of this one, it makes sense to include && in an answer.

First in words, inspired by Justin Johnson's comment:

  • || returns the first "truey" value, else the last value whatever it is.

  • && returns the first "falsey" value, else the last value whatever it is.

  • ?? returns the first non-null, non-undefined value, else the last value, whatever it is.

Then, demonstrated in live code:

let F1,
    F2 = null,
    F3 = 0,
    F4 = '',
    F5 = parseInt('Not a number (NaN)'),
    T1 = 3,
    T2 = 8

console.log( F1 || F2 || F3 || F4 || F5 || T1 || T2 ) // 3 (T1)
console.log( F1 || F2 || F3 || F4 || F5 )             // NaN (F5)

console.log( T1 && T2 && F1 && F2 && F3 && F4 && F5 ) // undefined (F1)
console.log( T1 && T2 )                               // 8 (T2)

console.log( F1 ?? F2 ?? F3 ?? F4 ?? F5 ?? T1 )       // 0 (F3)
console.log( F1 ?? F2)                                // null (F2)

肥爪爪 2024-07-19 14:03:37

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

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

注意:这在公共浏览器版本中还不常见。。 将随着可用性的变化而更新。

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

基本示例

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" }

浏览器支持 Jan '22 - 89%

Mozilla 文档

Logical nullish assignment, 2020+ solution

A new operator is currently being added to the browsers, ??=. This combines the null coalescing operator ?? with the assignment operator =.

NOTE: This is not common in public browser versions yet. Will update as availability changes.

??= checks if the variable is undefined or null, short-circuiting if already defined. If not, the right-side value is assigned to the variable.

Basic Examples

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

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

Object/Array Examples

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" }

Browser Support Jan '22 - 89%

Mozilla Documentation

逆光下的微笑 2024-07-19 14:03:37

是的,其提案现在进入第 4 阶段。 这意味着该提案已准备好纳入正式的 ECMAScript 标准。 您已经可以在最新的桌面版 Chrome、Edge 和 Firefox 中使用它,但我们还需要等待一段时间才能实现该功能的跨浏览器稳定性。

看一下下面的示例来演示其行为:

// note: this will work only if you're running latest versions of aforementioned browsers
const var1 = undefined;
const var2 = "fallback value";

const result = var1 ?? var2;
console.log(`Nullish coalescing results in: ${result}`);

前面的示例相当于:

const var1 = undefined;
const var2 = "fallback value";

const result = (var1 !== null && var1 !== undefined) ?
    var1 :
    var2;
console.log(`Nullish coalescing results in: ${result}`);

请注意,无效合并不会威胁虚假值,就像||运算符所做的那样(它只检查< code>undefined 或 null 值),因此以下代码片段将如下所示:

// note: this will work only if you're running latest versions of aforementioned browsers
const var1 = ""; // empty string
const var2 = "fallback value";

const result = var1 ?? var2;
console.log(`Nullish coalescing results in: ${result}`);


对于 TypesScript 用户,从 TypeScript 3.7 开始,这个功能现在也可用了。

Yes, and its proposal is Stage 4 now. This means that the proposal is ready for inclusion in the formal ECMAScript standard. You can already use it in recent desktop versions of Chrome, Edge and Firefox, but we will have to wait for a bit longer until this feature reaches cross-browser stability.

Have a look at the following example to demonstrate its behavior:

// note: this will work only if you're running latest versions of aforementioned browsers
const var1 = undefined;
const var2 = "fallback value";

const result = var1 ?? var2;
console.log(`Nullish coalescing results in: ${result}`);

Previous example is equivalent to:

const var1 = undefined;
const var2 = "fallback value";

const result = (var1 !== null && var1 !== undefined) ?
    var1 :
    var2;
console.log(`Nullish coalescing results in: ${result}`);

Note that nullish coalescing will not threat falsy values the way the || operator did (it only checks for undefined or null values), hence the following snippet will act as follows:

// note: this will work only if you're running latest versions of aforementioned browsers
const var1 = ""; // empty string
const var2 = "fallback value";

const result = var1 ?? var2;
console.log(`Nullish coalescing results in: ${result}`);


For TypesScript users, starting off TypeScript 3.7, this feature is also available now.

我的鱼塘能养鲲 2024-07-19 14:03:37

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

@Gumbo 的答案提供了检查 null 的最佳方法; 但是,请务必注意 JavaScript 中 ===== 的区别,尤其是在检查 问题时未定义和/或null

此处有一篇非常好的文章介绍了两个术语的区别。 基本上,如果您使用 == 而不是 ===,JavaScript 将尝试合并您正在比较的值并返回比较结果在合并之后

After reading your clarification, @Ates Goral's answer provides how to perform the same operation you're doing in C# in JavaScript.

@Gumbo's answer provides the best way to check for null; however, it's important to note the difference in == versus === in JavaScript especially when it comes to issues of checking for undefined and/or null.

There's a really good article about the difference in two terms here. Basically, understand that if you use == instead of ===, JavaScript will try to coalesce the values you're comparing and return what the result of the comparison after this coalescence.

素手挽清风 2024-07-19 14:03:37

请注意 JavaScript 中 null 的特定定义。 javascript 中“无值”有两种定义。
1. Null:当一个变量为null时,意味着它不包含任何数据,但是该变量已经在代码中定义了。 像这样:

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

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

window.alert(typeof myEmptyValue); // prints Object
  1. 未定义:当变量之前没有在代码中定义时,并且正如预期的那样,它不包含任何值。 像这样:

    if ( myUndefinedValue === undefined ) { window.alert('未定义');   } 
      // 警报 
      

如果是这种情况,变量的类型是“未定义”。

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

beware of the JavaScript specific definition of null. there are two definitions for "no value" in javascript.
1. Null: when a variable is null, it means it contains no data in it, but the variable is already defined in the code. like this:

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

in such case, the type of your variable is actually Object. test it.

window.alert(typeof myEmptyValue); // prints Object
  1. Undefined: when a variable has not been defined before in the code, and as expected, it does not contain any value. like this:

    if ( myUndefinedValue === undefined ) { window.alert('it is undefined'); }
    // alerts
    

if such case, the type of your variable is 'undefined'.

notice that if you use the type-converting comparison operator (==), JavaScript will act equally for both of these empty-values. to distinguish between them, always use the type-strict comparison operator (===).

原野 2024-07-19 14:03:37

这里有两项:

  1. 逻辑 OR

const foo = '' || '默认字符串';

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

  1. 空合并运算符

const foo = '' ?? '默认字符串';

控制台.log(foo); // 输出为空字符串,即 ''

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

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

There are two items here:

  1. Logical OR

const foo = '' || 'default string';

console.log(foo); // output is 'default string'

  1. Nullish coalescing operator

const foo = '' ?? 'default string';

console.log(foo); // output is empty string i.e. ''

The nullish coalescing operator (??) is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand.

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

浅忆 2024-07-19 14:03:37

请注意,React 的 create-react-app 工具链自 版本 3.3.0(2019 年 12 月 5 日发布)。 从发行说明来看:

可选链接和空合并运算符

我们现在支持可选链接和无效合并运算符!

// 可选链接 
  A?。();   // 如果 `a` 为 null/未定义,则未定义 
  公元前;   // 如果 `b` 为 null/未定义,则未定义 

  // 空合并 
  不明确的 ??   '其他一些默认值';   // 结果:'其他默认值' 
  无效的 ??   '其他一些默认值';   // 结果:'其他默认值' 
  ” ??   '其他一些默认值';   // 结果: '' 
  0 ??   300;   // 结果:0 
  错误的 ??   真的;   // 结果:假 
  

也就是说,如果您使用 create-react-app 3.3.0+,您现在就可以开始在 React 应用程序中使用 null-coalesce 运算符。

Note that React's create-react-app tool-chain supports the null-coalescing since version 3.3.0 (released 5.12.2019). From the release notes:

Optional Chaining and Nullish Coalescing Operators

We now support the optional chaining and nullish coalescing operators!

// Optional chaining
a?.(); // undefined if `a` is null/undefined
b?.c; // undefined if `b` is null/undefined

// Nullish coalescing
undefined ?? 'some other default'; // result: 'some other default'
null ?? 'some other default'; // result: 'some other default'
'' ?? 'some other default'; // result: ''
0 ?? 300; // result: 0
false ?? true; // result: false

This said, in case you use create-react-app 3.3.0+ you can start using the null-coalesce operator already today in your React apps.

回忆躺在深渊里 2024-07-19 14:03:37

它有望很快在 Javascript 中推出,因为截至 2020 年 4 月它正处于提案阶段。您可以在此处监控兼容性和支持的状态 - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator

对于使用 Typescript 的人,可以使用 空值合并运算符 来自 Typescript 3.7

来自文档 -

您可以将此功能(?? 运算符)视为“落下”的一种方式
处理 nullundefined 时返回”默认值。 什么时候我们
编写如下代码

让 x = foo ?? 酒吧();

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

It will hopefully be available soon in Javascript, as it is in proposal phase as of Apr, 2020. You can monitor the status here for compatibility and support - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator

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();

this is a new way to say that the value foo will be used when it’s “present”; but when it’s null or undefined,
calculate bar() in its place.

殤城〤 2024-07-19 14:03:37

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

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

可以使用这个,

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

Need to support old browser and have a object hierarchy

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

may use this,

(((body||{}) .head||{}) .eyes||[])[0] ||'left eye'
旧梦荧光笔 2024-07-19 14:03:37

ECMAScript 2021 启用了两个新功能:

  1. 空合并运算符 (??),这是一个逻辑运算符,当其左侧操作数是以下任一情况时,它会返回其右侧操作数null 或未定义,否则返回其左侧操作数。
let b = undefined ?? 5;

console.log(b); // 5

  1. 逻辑空赋值 (x ??= y) 运算符,仅当 x 具有空值(空或未定义)时才进行赋值。
const car = {speed : 20};
car.speed ??= 5;
console.log(car.speed);
car.name ??= "reno";
console.log(car.name);

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

有关 Nullish 合并运算符的更多信息可以在此处找到
https://developer.mozilla.org/en- US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator

ECMAScript 2021 enabled two new features:

  1. Nullish coalescing operator (??) which is a logical operator that returns its right-hand side operand when its left-hand side operand is either null or undefined, and otherwise returns its left-hand side operand.

let b = undefined ?? 5;

console.log(b); // 5

  1. Logical nullish assignment (x ??= y) operator which only assigns if x has a nullish value (null or undefined).

const car = {speed : 20};
car.speed ??= 5;
console.log(car.speed);
car.name ??= "reno";
console.log(car.name);

More about Logical nullish assignment can be found here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_nullish_assignment

More about Nullish coalescing operator can be found here
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator

南街九尾狐 2024-07-19 14:03:37

现在它在 Chrome、Edge、Firefox、Safari 等主流浏览器的最新版本中得到了全面支持。以下是 null 运算符和 Nullish Coalescing 运算符之间的比较

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

Now it has full support in latest version of major browsers like Chrome, Edge, Firefox , Safari etc. Here's the comparison between the null operator and Nullish Coalescing Operator

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
别念他 2024-07-19 14:03:37

使用 Babel 的用户需要升级到最新版本才能使用空值合并(??):

Babel 7.8.0 默认支持新的 ECMAScript 2020 功能:您
不需要启用单独的插件来进行无效合并(??),
使用预设环境不再可选链接 (?.) 和动态 import()

https ://babeljs.io/blog/2020/01/11/7.8.0

Those who are using Babel, need to upgrade to the latest version to use nullish coalescing (??):

Babel 7.8.0 supports the new ECMAScript 2020 features by default: you
don't need to enable individual plugins for nullish coalescing (??),
optional chaining (?.) and dynamic import() anymore with preset-env

From https://babeljs.io/blog/2020/01/11/7.8.0

妞丶爷亲个 2024-07-19 14:03:37

启用链式多个值/多个值

  • “短路”:如果第一个值之一有效,则不再进行任何评估,
  • 这意味着顺序很重要,最左边的值优先
const value = first ?? second ?? third ?? "default";

Chain multiple values / several values

  • "short circuit" is enabled: do not evaluate any further if one of the first values is valid
  • that means order matters, the most left values are prioritized
const value = first ?? second ?? third ?? "default";
伏妖词 2024-07-19 14:03:37

我试图检查输入是否为空,然后相应地使用该值。 这是我的代码。

let valueToBeConsidered = !inputValue ? "trueCondition" : "falseCondition",

因此,如果 inputValue 为 null,则 valueToBeConsidered = falseCondition,如果 inputValue 有值,则 valueToBeConsidered = trueCondition

I was trying to check if an input is null and then use the value accordingly. This is my code.

let valueToBeConsidered = !inputValue ? "trueCondition" : "falseCondition",

So if inputValue is null then valueToBeConsidered = falseCondition and if inputValue has a value then valueToBeConsidered = trueCondition

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文