[英]Javascript - avoiding asynchronous race condition when checking object property existence
[英]Javascript - how to avoid multiple if condition checks when checking if object has a property?
我怎样才能避免这么长的 if 条件?
if (typeof window.checkoutConfig.shipping !== "undefined") {
if (typeof window.checkoutConfig.shipping.rules !== "undefined") {
if (typeof window.checkoutConfig.shipping.rules.express !== "undefined") {
if (typeof window.checkoutConfig.shipping.rules.express.express_note !== "undefined") {
this.expressNote(window.checkoutConfig.shipping.rules.express.express_note || "");
}
}
}
}
有没有我可以使用的方法,例如(伪代码): isset(window.checkoutConfig.shipping.rules.express.express_note)
。
你可以试试。
try {
this.expressNote(window.checkoutConfig.shipping.rules.express.express_note || "");
} catch (e) {
// meh
}
ES2020 引入了可选链,以防止像Cannot read property of undefined
这样的错误。 加个? 在每个可选属性之前: window.checkOutConfig.shipping?.rules?.express?.express_note
如果属性不存在则返回undefined
但如果存在则返回属性值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.