Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
866 views
in Technique[技术] by (71.8m points)

javascript - for in loop in IE11

console in IE 11

enter image description here

console in Chrome

enter image description here

If I change word 'item' in the loop to 'anotherItem' like this

var obj = {
    id1: 'item 1',
    id2: 'item 2',
    id3: 'item 3'    
};
for (anotherItem in obj){
    console.log(anotherItem);
}

The cycle works fine

Why IE 11 does not process word 'item'

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

item is defined as a native function in IE, and is probably read-only, and therefore is the reason you cannot change it's value.

Prior to Edge, Microsoft didn't like adhering to standards, and introduced all sorts of features that aren't in the standards. The item function is not present in Edge.

Also, you haven't declared anotherItem, try this:

Try this:

var obj = {
    id1: 'item 1',
    id2: 'item 2',
    id3: 'item 3'    
};

for (var anotherItem in obj){
    console.log(anotherItem);
}

If you don't declare a variable with the var keywork, and you're not in strict-mode, it will be defined as a global variable (which is not what you want). Global variables are essentially properties on the global object, and in the context of a web browser, that'd be the window object.

Add the following to the top of your JS file to enable strict mode, and then you won't be able to make these mistakes in the first place as an exception will be thrown.

"use strict";

You can also choose to enable strict mode for specific functions, like this:

(function() {
    "use strict";
    // code here is in strict mode
})()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...