在JavaScript中,是否有更简单的方法来检查属性的属性是否存在? [英] In JavaScript, is there an easier way to check if a property of a property exists?

查看:105
本文介绍了在JavaScript中,是否有更简单的方法来检查属性的属性是否存在?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种简单的方法可以本地确定JavaScript中对象中是否存在深层属性?例如,我需要访问这样的属性:

Is there an easy way to natively determine if a deep property exists within an object in JavaScript? For example, I need to access a property like this:

var myVal = appData.foo.bar.setting;

但有可能foo,foo.bar或foo.bar.setting都没有已定义。在Groovy中,我们可以这样做:

But there is a chance that either foo, foo.bar, or foo.bar.setting has not been defined yet. In Groovy, we can do something like this:

def myVal = appData?.foo?.bar?.setting

有没有类似的方法在JavaScript中执行此操作,而无需编写自定义函数或嵌套if语句?我发现这个答案很有用,但是希望有更优雅,更少自定义的方式。

Is there a similar way to do this in JavaScript, without having to write a custom function or nested if statements? I've found this answer to be useful, but was hoping there was a more elegant and less custom way.

推荐答案

我觉得这很方便:

var myVal = (myVal=appData) && (myVal=myVal.foo) && (myVal=myVal.bar) && myVal.settings;

如果属性存在,将尝试下一部分序列。

If a property exists, the next part of the sequence will be attempted.

&& 之前的表达式求值为false时,不会检查表达式的下一部分。如果未定义 myVal.appData.foo.bar.settings 中的任何一个,则 myVal 的值( undefined (评估为 false

When the expression before && evaluates to false, the next part of the expression will not be checked. If either of myVal.appData.foo.bar.settings is not defined, the value of myVal (undefined( will evaluate to false.

这篇关于在JavaScript中,是否有更简单的方法来检查属性的属性是否存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆