views:

159

answers:

2

I have the following function (worked in IE6 but is broken in IE8)

function implode() { var str = '';
    for(item in globvars)  //<- IE8 wets itself here ...
       str+= '\n' + globvars[item]+';';
    return str+'\n';
}

It seems an innocuous little function, but IE8 dosent grok it. Can anyone show me how to rewrite this so it work in IE8 (as well as the other browsers)?

[Edit]

At the begining of the script (i.e. first line after the tag, I have defined the globvars like this:

var globvars = new Array();  // This should give globvars global scope

The error from IE8 is:

Object does not support this action

+2  A: 

I use this syntax in IE all the time with no problem.

Have you tried:

function implode() { var str = ''; 
    for(var item in globvars)  //<- IE8 wets itself here ... 
       str+= '\n' + globvars[item]+';'; 
    return str+'\n'; 
} 

If item is used globally elsewhere, it may be creeping in to your function's scope. Throwing in var scopes item to the current function.

josh3736
+1: I scoped the variable 'item' locally (by prefixing it withthe keyword var), and that seems to have stopped IE8 complaining. The odd thing though, is that I DO NOT have a variable named item anywhere else in my script. I'll have to investigate this further ...
morpheous
+4  A: 

I DO NOT have a variable named item anywhere else in my script

You will, however, have an element with id="item" or name="item". IE mirrors elements with an id/name not just as document.item but also window.item. (Obviously it's bad practice to rely on either.)

So when you say item= without telling it you want a var, silly IE thinks you're trying to assign to the existing HTMLElement with that id/name sitting in the window, and throws a fit because elements aren't writable. This is one reason to always use var even for global variables.

You shouldn't use for...in to iterate an Array. It doesn't do what you think. It may return the array items in the wrong order, and potentially unexpected non-numeric properties. Always use the plain old for (var i= 0; i<array.length; i++) loop for getting the items in an Array; for...in is only for Object used as a mapping.

Anyhow, JavaScript's built-in join() almost does the work for you:

function implode() {
    return '\n'+globvars.join(';\n')+';\n';
}
bobince
excellent answer
Már Örlygsson
+1 cool. didn't know that
morpheous