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. In that case, you can loop through it with for( var key in map )
. Aim to fix the source of errors instead of fighting the symptoms.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.