问题描述
这是我在Javascript中经常遇到的问题.假设我有一个这样的对象:
This is something that I come up against quite often in Javascript. Let's say I have an object like this:
var acquaintances = {
types: {
friends: {
billy: 6,
jascinta: 44,
john: 91
others: ["Matt", "Phil", "Jenny", "Anna"]
},
coworkers: {
matt: 1
}
}
}
在我的理论程序中,我唯一确定的是熟人
是一个对象;我不知道是否已设置 acquaintances.types
,还是在其中设置了 friends
.
In my theoretical program, all I know for sure is that acquaintances
is an object; I have no idea whether acquaintances.types
has been set, or whether friends
has been set within it.
如何有效检查 acquaintances.types.friends.others
是否存在?
How can I efficiently check whether acquaintances.types.friends.others
exists?
我通常要做的是:
if(acquaintances.types){
if(aquaintances.types.friends){
if(acquaintances.types.friends.others){
// do stuff with the "others" array here
}
}
}
除了费力之外,这些嵌套的 if
语句还有些难以管理(实际上,我的对象所具有的层次远不止于此!).但是,如果我只是尝试一下 if(acquaintances.types.friends.others){)
之类的东西,而尚未设置 types
,那么该程序将崩溃.
Aside from being laborious, these nested if
statements are a bit of a nightmare to manage (in practice my objects have far more levels than this!). But if I were to just try something like if(acquaintances.types.friends.others){)
straight off the bat, and types
hasn't been set yet, then the program will crash.
Javascript以一种简洁,可管理的方式实现此目的的方式是什么?
What ways does Javascript have of doing this in a neat, manageable way?
推荐答案
另一种方法是:
((acquaintances.types || {}).friends || {}).others
比其他解决方案要短,但可能会让您激动不已.
which is shorter than other solutions, but may or may not thrill you.
您还可以构建一个小助手,以使相同的想法更可口:
You can also build a little helper to make the same idea a tiny bit more palatable:
function maybe(o) { return o || {}; }
现在您可以做
maybe(maybe(acquaintances.types).friends).others
如果您不介意将属性名称编写为字符串,则可以提供一些帮助:
If you don't mind writing property names as strings, you could make a little helper:
function maybe(obj) {
return Object.defineProperty(
obj || {},
'get',
{ value: function(prop) { return maybe(obj[prop]); }
);
}
现在您可以写
maybe(acquaintances.types').get('friends').others
在ES6中,您可以使用默认值的解构分配来做到这一点,虽然很笨拙:
In ES6, you can do this, albeit clumsily, using destructuring assignment with defaults:
var { types: { friends: { others } = {} } = {} } = acquaintances;
如果要在表达式上下文中使用它,而不是分配给变量,则理论上可以使用参数解构:
If you want to use this in an expression context, instead of assigning to a variable, in theory you could use argument destructuring:
(({ types: { friends: { others } = {} } = {} }) => others)(acquaintances)
说了一切之后,标准方法仍然存在
After all is said and done, the standard approach remains
acquaintances.types &&
acquaintances.types.friends &&
acquaintances.types.friends.others
这就是为什么在其中有活跃的(?)讨论ES6设计小组讨论了类似CoffeeScript的存在运算符,但似乎收敛速度不是很快.
This is why there is an active (?) discussion in the ES6 design groups about a CoffeeScript-like existential operator, but it does not seem to be converging very rapidly.
这篇关于检查未知对象中是否存在对象的最有效的Javascript方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!