[英]Javascript 'Uncaught TypeError: Cannot read property 'blah' of undefined '
I'm trying to test if an array element is undefined: 我正在尝试测试数组元素是否未定义:
if(typeof selected[i].facet != 'undefined')
{
//do stuff
}
gives me 给我
Javascript 'Uncaught TypeError: Cannot read property 'facet' of undefined '
您必须同时测试数组索引和属性:
if (selected[i] && selected[i].facet !== undefined) { // ...
if((selected[i]) && (selected[i].facet != undefined))
{
//do stuff
}
You should just do your loop properly 您应该正确地执行循环
for (var i = 0, len = selected.length; i < len; ++i) {
//selected[i] will always be a valid index in the array
}
Should it be the case that selected[i]
is a valid index in the array, but undefined
regardless, then you don't semantically need an array but a dictionary with integers as keys. 如果selected[i]
是数组中的有效索引,但是无论如何都undefined
,那么在语义上就不需要数组,而需要一个以整数作为键的字典。 In that case, you can loop through it with for( var key in map )
. 在这种情况下,您可以使用for( var key in map )
遍历它。 Aim to fix the source of errors instead of fighting the symptoms. 旨在修复错误的来源,而不是消除症状。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.