我在这样的代码条件行中遇到过someObject.arrParam?.length。那是什么语法?那个问号的东西怎么叫?我知道一个用于函数参数的可选运算符。这是它的用法变化吗?以前没见过。
参数后的问号如 obj.val?.prop
IT技术
javascript
2021-01-31 10:22:36
3个回答
这在 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 wont
这是在最新的 ESNext 迭代中作为新功能引入的。
NodeJS 支持:https : //node.green/#ES2020-features-optional-chaining-operator-----
当前浏览器支持:https : //caniuse.com/#feat=mdn-javascript_operators_optional_chaining
更多细节在这里:https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining
这称为可选链(或条件链),它基本上将评估整个表达式,就undefined好像arrParam是undefined或 一样null。
它被称为“条件(三元)运算符”。
result=condition?ifTrue:ifFalse
在 中x=(y>10)?100:1,如果 y>10,则 x 设置为 100,否则,x 设置为 1。
相当于:
if(y>10) x=100;
else x= 1;
其它你可能感兴趣的问题