开发者

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' + 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


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜