Javascript feature works in FF, Opera, etc., does not work in IE8 - how to fix

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

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

      

It seems like a harmless little feature, but IE8 dosent grok it. Can someone show me how to rewrite this to make it work in IE8 (as well as other browsers)?

[change]

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

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

      

IE8 error:

Object does not support this action

+2


a source to share


2 answers


I don't have a variable named item elsewhere in the script

However, you must have an element with id="item"

or name="item"

. IE reflects elements with id / name not only as document.item

, but also window.item

. (Obviously, relying on bad practice too).

So when you say item=

without telling it what you want var

, silly IE thinks you are trying to assign an existing HTMLElement with that id / name sitting in window

and throws it away because the elements are not writable. This is one reason to always use it var

even for global variables.



Cannot be used for...in

to iterate over an array. It doesn't do what you think it does. It can return array elements in the wrong order and potentially unexpected non-numeric properties. Always use a simple old loop for (var i= 0; i<array.length; i++)

to get elements in an array; for...in

used only for Object

used as display.

Anyway, inline JavaScript join()

works almost for you:

function implode() {
    return '\n'+globvars.join(';\n')+';\n';
}

      

+10


a source


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

You tried:



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

      

If item

used globally elsewhere, it may fall within the scope of your function. Dropping var

areas item

into the current function.

+3


a source







All Articles