【发布时间】:2023-03-18 04:35:02
【问题描述】:
通常在检查特定属性是否有值时,您必须遍历一些对象属性或数组。这会导致像下面这样的长语句,只是为了避免error can't read property ____ of undefined。
有没有办法更简洁地写这个?可能 ES6 有什么?我想我记得一些像 Lodash 这样的库提供了帮助方法但找不到它们。
if (
user &&
user.profile.pets &&
user.profile.pets[0] &&
user.profile.pets[0].type === "dog"
) {
【问题讨论】:
-
get?
-
您正在寻找的 lodash 方法可能是
_.get,但除此之外 es6 没有提供其他方法来缩短它。然而,a proposal for safe property access 使用?.语法,但在有人支持它之前还有很长的路要走。
标签: javascript lodash