我在代码条件行中遇到了这样的情况someObject.arrParam?.length。那是什么语法?这个问号的东西怎么称呼?我知道一个可选运算符,用于函数中的参数。这是它的用法的变体吗?以前从未见过面。
这在 JavaScript 中称为可选链。它允许深入研究对象而不引发空异常。
例如:尝试运行下面的代码片段,然后取消注释该行并运行它以了解工作示例。
let employeeA ={ name: "Dane", address : { city:"London"}}
let employeeB ={ name: "John"}
console.log(employeeA.address.city)
// console.log(employeeB.address.city) <---- this will raise an error
console.log(employeeB.address?.city) // <--- this wontRun Code Online (Sandbox Code Playgroud)
这是最新 ESNext 迭代中作为新功能引入的。
NodeJS 支持:https://node.green/#ES2020-features-optional-chaining-operator-----
当前浏览器支持:https://caniuse.com/#feat=mdn-javascript_operators_optical_chaining
更多详细信息请参见: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining