开发者

IE8 will report error about for in without declaring var item?

开发者 https://www.devze.com 2022-12-13 18:36 出处:网络
Like : var resul开发者_StackOverflow社区t = eval(\'(\' + response + \')\'); var html = value = \'\';

Like :

var resul开发者_StackOverflow社区t = eval('(' + response + ')');
var html = value = '';

for(item in result)
{

}

response is a json response.

It stops at for.. in IE8.

How to fix that?

EDIT

I got the same error when running:

result = [1,2,3];
for(item in result)
{
...
}


I tested the code from JavaScript For...In Statement in IE8, no issue.

Definitely not an issue of the loop (not working in IE8) but what is in the 'result' object.

UPDATE:

I found the issue.

In IE8 (not sure about other IE versions) the word "item" somehow is a reserved word or something.

This will work:

var item;
for(item in result)
{
...
}

This will not (if item is not declared):

for(item in result)
{
...
}

This will work:

for(_item in result)
{
...
}


You should declare item explicitly with var. The standard idiom for using for..in is as follows and should only be used for iteration over objects (not arrays):

for ( var item in result ) {
    if ( !result.hasOwnProperty(item) ) {
        // loop body goes here
    }
}
0

精彩评论

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