-1

我从MDN复制粘贴的示例代码,但可选链接在我的节点(v12.13.0)REPL 中不起作用。抛出一个语法错误,指出问号后面的点无效。这是怎么回事 ?我已经在 React App 中使用过这个表达式,它似乎工作正常。

const adventurer = {
  name: 'Alice',
  cat: {
    name: 'Dinah'
  }
};


const dogName = adventurer.dog?.name;
console.log(dogName);
// expected output: undefined

console.log(adventurer.someNonExistentMethod?.());
// expected output: undefined

4

1 回答 1

6

它仅适用于 --harmony 下的 Node 14: 如何在 Node.js 12 中使用可选链接

如果您想在节点中使用此功能,可以使用 babel 可选链接插件: https ://babeljs.io/docs/en/next/babel-plugin-syntax-optional-chaining.html

于 2020-09-19T05:09:22.060 回答