[英]JavaScript proper way to handle null in JSON object
Here is the code : 这是代码:
for (i = 0; i < data.RecruitingGroups.length; i++) {
data.RecruitingGroups[i].id = i;
if (data.RecruitingGroups[i].Rule.Rules != null) {
for (j = 0; j < data.RecruitingGroups[i].Rule.Rules.length; i++) {
data.RecruitingGroups[i].Rule.Rules[j].id = j;
}
}
}
Problem is that sometimes RecruitingGroups[].Rule is null. 问题是有时RecruitingGroups []。Rule为空。 So I tried to verify it was not null before continuing and running the next for loop, but it still throws the error: 因此,我尝试在继续并运行下一个for循环之前验证它是否不为null,但仍会引发错误:
Uncaught TypeError: Cannot read property 'Rules' of null 未捕获的TypeError:无法读取null的属性“ Rules”
How can i bypass this error. 我如何绕过此错误。
You're testing if Rule.Rules
is null
. 您正在测试Rule.Rules
是否为null
。 That's not the problem; 那不是问题; Rule
itself is null
, as evidenced by the error message. Rule
本身为null
,如错误消息所示。 You need to test both Rule
and Rule.Rules
if either can be null. 如果两者都可以为null,则需要同时测试Rule
和Rule.Rules
。
Try 尝试
if (data.RecruitingGroups[i].Rule && data.RecruitingGroups[i].Rule.Rules) {
your second loop needs to increment j++
not i++
. 您的第二个循环需要递增j++
而不是i++
。 =) =)
if (data.RecruitingGroups[i].Rule && data.RecruitingGroups[i].Rule.Rules) {
for (j = 0; j < data.RecruitingGroups[i].Rule.Rules.length; i++) {
data.RecruitingGroups[i].Rule.Rules[j].id = j;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.