最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - TypeError: is null - Stack Overflow

programmeradmin2浏览0评论

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.

Share Improve this question edited Jan 20, 2016 at 0:52 Michał Perłakowski 92.9k30 gold badges163 silver badges187 bronze badges asked Nov 17, 2011 at 17:56 airnetairnet 2,6936 gold badges33 silver badges37 bronze badges 1
  • 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
Add a ment  | 

2 Answers 2

Reset to default 3

You 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
发布评论

评论列表(0)

  1. 暂无评论