参数后的问号如 obj.val?.prop

IT技术 javascript
2021-01-31 10:22:36

我在这样的代码条件行中遇到过someObject.arrParam?.length那是什么语法?那个问号的东西怎么叫?我知道一个用于函数参数可选运算符这是它的用法变化吗?以前没见过。

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好像arrParamundefined或 一样null

它被称为“条件(三元)运算符”。

result=condition?ifTrue:ifFalse

在 中x=(y>10)?100:1,如果 y>10,则 x 设置为 100,否则,x 设置为 1。

相当于:

if(y>10) x=100;
else     x=  1;
不,不是这样。
2021-03-24 10:22:36