[英]Conditional chaining in JS false if not found
In JS's optional chaining (I don't think it's implemented in current versions), can I have it evaluate to false if not found?在 JS 的可选链中(我不认为它在当前版本中实现),如果找不到,我可以让它评估为 false 吗?
var obj = {a: {foo: "bar"}}
console.log(obj.a?.foo); //bar
console.log(obj.b?.foo); //this is undefined, I want it to be false
I read Optional Chaining in JavaScript and Null-safe property access (and conditional assignment) in ES6/2015 but neither answered my question.我阅读了 ES6/2015 中的Optional Chaining in JavaScript和Null-safe property access (and conditional assignment),但都没有回答我的问题。
You can use !!
你可以用
!!
or != null
(pay attention != not !== to check both undefined and null)或
!= null
(注意 != not !== 检查 undefined 和 null)
var obj = {a: {foo: "bar"}}; console.log(!!obj.b?.foo); console.log(obj.b?.foo != null);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.