另一种方法是:
((acquaintances.types || {}).friends || {}).others
它比其他解决方案更短,但可能会或可能不会让您兴奋。
您还可以构建一个小助手,使相同的想法更容易接受:
function maybe(o) { return o || {}; }
现在你可以做
maybe(maybe(acquaintances.types).friends).others
如果您不介意将属性名称写为字符串,您可以制作一个小助手:
function maybe(obj) {
return Object.defineProperty(
obj || {},
'get',
{ value: function(prop) { return maybe(obj[prop]); }
);
}
现在你可以写
maybe(acquaintances.types').get('friends').others
在 ES6 中,您可以使用带有默认值的解构赋值来做到这一点,尽管很笨拙:
var { types: { friends: { others } = {} } = {} } = acquaintances;
如果您想在表达式上下文中使用它,而不是分配给变量,理论上您可以使用参数解构:
(({ types: { friends: { others } = {} } = {} }) => others)(acquaintances)
归根结底,标准方法仍然存在
acquaintances.types &&
acquaintances.types.friends &&
acquaintances.types.friends.others
这就是为什么有一个活跃的(?)讨论在 ES6 设计组中,有一个类似 CoffeeScript 的存在运算符,但它似乎并没有很快收敛。