Domanda

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");
  • What other vars will crash besides null and undefined?
  • How to prevent this from happening?
È stato utile?

Soluzione 3

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)

Altri suggerimenti

You're going to get a TypeError stating undefined has no properties. Nothing you can do here but wrap it in a try catch for TypeErrors.

Note that this is the same reason referencing a property on something that evaluates to undefined will return a ReferenceError: undefined should never have properties.

You can just check for null without doing a type specific check, that will catch undefined values also.

var i, len, arr;
arr = [true, ["elm_0"], 99, "abc", null, undefined];
for (i = 0, len = arr.length; i < len; i++) {
    if (arr[i] != null) {
        console.log(arr[i].length);
    }
}
console.log("I was executed");

Try this:

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++){

try{
console.log(arr[i].length);
}Catch(e){console.log(0);}
}

console.log("I was executed");

If your only goal is to determine if one of these objects is an array, then instead of:

for(i = 0, len = arr.length ; i<len ; i++){
    console.log(arr[i].length);
}

You should try this:

for(i = 0, len = arr.length ; i<len ; i++){
    if (arr[i] instanceof Array)
        console.log(arr[i].length);
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top