1

Every time I pass an array to this function, when it hits a null or undefined value it stops the loop. I can't work out how to fix this. When I ask whether the current item in the loop is null or undefined or false, it doesn't answer...

function xul(func, loc, arr){
var elem;
var props = {};

for (var i = 0, len = arr.length; i < len; i++){
    if (arr[i] == undefined) {
        jsdump("undefined" + " - " + len);
    }
    else if (arr[i] == null) {
        jsdump("null" + " - " + len);
    }
    else if (arr[i] == false) {
        jsdump("false" + " - " + len);
    }
    else if (typeof arr[i] == "string"){
        elem = arr[i];
        if (typeOf(arr[i + 1]) == "object") {
            props = arr[i+1];
            i++;
        }
        loc = createNode(func, loc, elem, props);   
    }
    if (typeOf(arr[i + 1]) == "array") {
        xul("append", loc, arr[i+1]);
    } else {
        return loc;
    }   
}
}

What is going on here?

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
cybermotron
  • 987
  • 2
  • 10
  • 29

1 Answers1

3

Actually the loop stops here (if you return something you exit the loop!):

if (typeOf(arr[i + 1]) == "array") {
    xul("append", loc, arr[i+1]);
} else {
    return loc;
}  

if the next element it's not an array it returns loc and the loop stops. check this fiddle: http://jsfiddle.net/g8SVJ/ it logs two undefined and then returns loc

You should also use === instead of ==

Nicola Peluchetti
  • 76,206
  • 31
  • 145
  • 192