javascript 无法读取 null 的属性“名称”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19303187/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Cannot read property 'name' of null
提问by Darkagelink
So my problem is that sometimes data.content[i].location.name
returns an error saying cannot read property 'name' of null.
所以我的问题是有时会data.content[i].location.name
返回一个错误,说无法读取 null 的属性“名称”。
for ( var i = 0; i < len; i++ ) {
classes.push({
"id":data.post[i].id,
"location":data.content[i].location.name,
"type":data.content[i].type
});
}
How can i fix this issue? I need data.content[i].location.name if it is not null.
我该如何解决这个问题?如果 data.content[i].location.name 不为空,我需要它。
回答by Tom Swifty
Just do a check if (data.content[i].location.name != null) before doing your push
在推送之前检查 if (data.content[i].location.name != null)
If you want something special to happen in the case where it is null you can do that in the else.
如果你想在它为空的情况下发生一些特殊的事情,你可以在 else 中做到这一点。
Or as you've indicated sometimes location is null, so check that too the same way.
或者正如您所指出的,有时位置为空,因此也以相同的方式检查。
回答by Travis J
Test for the property using .hasOwnPropertyto prevent getting the error
使用.hasOwnProperty测试属性以防止出现错误
for ( var i = 0; i < len; i++ ) {
classes.push({
"id":data.post[i].id,
"location": data.content[i].location.hasOwnProperty?("name") ? data.content[i].location.name : "",
"type":data.content[i].type
});
}