我遇到了这样的代码条件语句:someObject.arrParam?.length
。这是什么语法?那个问号叫什么?我知道一个用于函数参数的可选运算符。这是它的变体吗?以前从未遇到过。
我遇到了这样的代码条件语句:someObject.arrParam?.length
。这是什么语法?那个问号叫什么?我知道一个用于函数参数的可选运算符。这是它的变体吗?以前从未遇到过。
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
这被称为 "条件(三元)运算符".
result=condition?ifTrue:ifFalse
在 x=(y>10)?100:1
中,如果 y>10,则 x 被设置为 100,否则 x 被设置为 1。
相当于:
if(y>10) x=100;
else x= 1;