如何检查对象中的对象是否存在
似乎以下用于检查对象成员是否存在的技术会产生错误,因为在检查之前尚未声明“bar”父对象,这意味着我要么必须在检查之前声明它,要么使用两个“typeof”表达式,其中任何一个都是多余的代码:
var foo = {},
newVal = (typeof foo.bar.myVal !== 'undefined' ? foo.bar.myVal : null );
Error: foo.bar is undefined
那么,如何检查未声明对象中的成员是否存在而不产生错误?
我喜欢 JavaScript,但有时...
It seems that the following technique for checking the existence of an object member produces an error because the 'bar' parent object hasn't been declared before the check, which means I either have to declare it before the check or use two 'typeof' expressions, either of which would be excess code:
var foo = {},
newVal = (typeof foo.bar.myVal !== 'undefined' ? foo.bar.myVal : null );
Error: foo.bar is undefined
So, how do you check if a member within an undeclared object exists without producing an error?
I love javascript, but sometimes...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
只需使用下面的代码即可完成:
属性为 null 或未定义,它将被评估为 false,因此上面的代码只会处理第一个“false”语句。
It can be done simply using the code below:
A property is null or undefined, it will be evaluated as false so the above code will only process up to the first 'false' statement.
公平地说,JavaScript 读起来几乎就像自然语言一样。
To be fair to javascript, that reads almost like natural language.
最简单的测试是:
The simplest test is:
您可以将其包装到一个方法中:
您可以将其称为:
You could wrap it up into a method:
Where you could call it as:
正如 Matthew Abbott 在他的回复中给出的那样,如果你做了很多事情,你可以编写一个方法供以后使用它深入研究子属性,其中整个对象或链上的某个位置可以为空。下面是我使用 lodash 的实现。
您可以像这样调用该方法:
As Matthew Abbott gave in his response, you can write a method for it to use it later if you do a lot of diving into child properties where the whole object or somewhere along the chain can be null. Below is my implementation using lodash.
You can call the method like this:
还有另一种方法是使用 JS 转译器,例如 Babel:
There is another way is you use a JS transpiler like Babel: