简体   繁体   中英

Nullish coalescing assignment operator (??=) in NodeJS

I'm trying to use the Nullish coalescing assignment operator (??=) in NodeJS, it is possible?

const setValue = (object, path, value) => {
  const indices = {
      first: 0,
      second: 1
    },
    keys = path.replace(new RegExp(Object.keys(indices).join('|'), 'g'), k => indices[k]).split('.'),
    last = keys.pop();

  keys
    .reduce((o, k, i, kk) => o[k] ??= isFinite(i + 1 in kk ? kk[i + 1] : last) ? [] : {}, object)[last] = value;

  return obj;
}
est.js:9
       .reduce((o, k, i, kk) => o[k] ??= isFinite(i + 1 in kk ? kk[i + 1] : last) ? [] : {}, object)
                                      ^

SyntaxError: Unexpected token '?'
        at wrapSafe (internal/modules/cjs/loader.js:1067:16)
        at Module._compile (internal/modules/cjs/loader.js:1115:27)
        at Object.Module._extensions..js (internal/modules/cjs/loader.js:1171:10)
        at Module.load (internal/modules/cjs/loader.js:1000:32)
        at Function.Module._load (internal/modules/cjs/loader.js:899:14)
        at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
        at internal/main/run_main_module.js:17:47

The error means your version of Node does not yet have support for the ??= operator.

Check out the versions which support it on node.green :

在此处输入图像描述

The node version you are using doesn't support the nullish coalescing assignment operator.

It's possible for node version v15.14+.

The rewrite for something like

a.greeting ??= "hello"

in node <v15.14 is:

a.greeting = a?.greeting ?? 'hello'

Maybe it does help someone:]

You could replace logical nullish assignment ??=

o[k] ??= isFinite(i + 1 in kk ? kk[i + 1] : last) ? [] : {}

with an assignment with logical OR ||

o[k] = o[k] || (isFinite(i + 1 in kk ? kk[i + 1] : last) ? [] : {})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM