admin管理员组文章数量:1393069
I have a situation where I declare an object var o = null;
Then, I pass it into a function, do stuff and maybe assign an object to it.
Later on, I execute parse(o.page)
.
If o
is null, then I get "TypeError: o.page is null",
and the program stops there because I'm trying to get the property of a null value.
I know one solution could be to initially assign null to all of o
's properties.
Just wondering if there is a more subtle way to handle this error.
because I would like to handle parse1(o);
and parse2(o.page1)
where o
can be null.
I have a situation where I declare an object var o = null;
Then, I pass it into a function, do stuff and maybe assign an object to it.
Later on, I execute parse(o.page)
.
If o
is null, then I get "TypeError: o.page is null",
and the program stops there because I'm trying to get the property of a null value.
I know one solution could be to initially assign null to all of o
's properties.
Just wondering if there is a more subtle way to handle this error.
because I would like to handle parse1(o);
and parse2(o.page1)
where o
can be null.
- If you show more of your code, I guess there would be a way to create an elegant solution that avoids the problem altogether. – Tomalak Commented Nov 17, 2011 at 18:11
2 Answers
Reset to default 3You could use the ternary operator to do this:
parse2(o ? o.page1 : null)
There is no way to get o.page
to work on its own when o
is null
.
Other ways exist, for example returning {}
instead of null
, as calling nonexistent properties yields undefined
instead of throwing an error.
Generally speaking, avoiding a situation where invalid calls linger in your code is remendable. Either you check the return value before you use it (like above), or you don't return values that can invalidate subsequent code.
Instead of null
, assign an empty object.
var o = {};
You cannot assign a property to o
if it is null
. That would result in
TypeError: Cannot set property 'propname' of null
本文标签: javascriptTypeError is nullStack Overflow
版权声明:本文标题:javascript - TypeError: is null - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744773004a2624455.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论