JavaScript“无法读取属性”栏“未定义的 [英] JavaScript "cannot read property "bar" of undefined

查看:191
本文介绍了JavaScript“无法读取属性”栏“未定义的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带3个参数的函数。我遇到的问题之一是参数之一是有时未定义的Object值的属性(即它需要 thing.foo.bar ,有时 thing.foo 未定义,因此无法访问 bar )。

I've got a function that takes 3 parameters. The problem I have is one of the parameters is a property of a sometimes undefined value of an Object (i.e. it takes in thing.foo.bar, and sometimes thing.foo is undefined, so it can't access bar).

有什么方法可以解决这个问题?在函数的声明中,我有一个条件检查:
if(!parameterName),但是浏览器(Chrome)仍然抛出一个它不能的错误阅读undefined的 bar 属性。

What's a way around this? Within the function's declaration, I have a conditional checking: if (!parameterName), but the browser (Chrome) is still throwing an error that it can't read the bar property of undefined.

推荐答案

如果对象的属性可能引用其他一些对象那么您可以在尝试使用其属性之前测试 是否为undefined:

If an object's property may refer to some other object then you can test that for undefined before trying to use its properties:

if (thing && thing.foo)
   alert(thing.foo.bar);

如果您显示一些实际代码,我可以更新我的答案以更好地反映您的情况,但可能会像这个:

I could update my answer to better reflect your situation if you show some actual code, but possibly something like this:

function someFunc(parameterName) {
   if (parameterName && parameterName.foo)
       alert(parameterName.foo.bar);
}

这篇关于JavaScript“无法读取属性”栏“未定义的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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