Skip to content Skip to sidebar Skip to footer

Javascript Function Works In Ff, Opera Etc, Fails In Ie8 - How To Fix

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'

Solution 1:

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';
}

Solution 2:

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.

Post a Comment for "Javascript Function Works In Ff, Opera Etc, Fails In Ie8 - How To Fix"