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?

5
  • are you sure the array itself isn't null? Commented Jul 10, 2011 at 18:04
  • 1
    typeof can never return array Commented Jul 10, 2011 at 18:06
  • In the last 'if', if it's undefined or null it goes in the else and 'return' stops the loop Commented Jul 10, 2011 at 18:07
  • @SLaks: Ah, but he used typeOf, not typeof. ;) Commented Jul 10, 2011 at 18:10
  • 1
    Very right typeOf is little function I found on my travels... its just a normal typeof, but then it checks if it returns object whether you can read its length... if you can its an array! Commented Jul 10, 2011 at 18:21

1 Answer 1

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 ==

Sign up to request clarification or add additional context in comments.

1 Comment

Haha... I just slapped my self in the forehead... I don't know how I missed that!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.