I have a big array which contains all kind of types (booleans, arrays, null, ...), and I am trying to access their propiety arr[i].length
, but some of them obiously fail to have length.
I wouldn't mind if the guys missing length returned undefined
(I could simply use arr[i].length||0
or something like that), but this is not the case, the whole thing crashes with some values (null
or undefined
for example).
var i, len, arr;
arr = [true, ["elm_0"], 99, "abc"]; //crashes if you add 'null' or 'undefined'
for(i = 0, len = arr.length ; i<len ; i++){
document.write(arr[i].length + "<br>");
}
document.write("I was executed");
null
and undefined
?Check for arr[i]
before arr[i].length
var i, len, arr;
arr = [true, ["elm_0"], 99, "abc"];
if(arr) for(i = 0, len = arr.length || 0 ; i<len ; i++){
if(arr[i]) document.write((arr[i].length || 0) + "<br>");
else document.write(0 + "<br>"); // what to do if no arr[i]
}
document.write("I was executed");
You can use a ternary operator, too (arr[i]?arr[i].length||0:0)