用于IE11中的循环 [英] for in loop in IE11

查看:144
本文介绍了用于IE11中的循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在IE 11中的控制台

Chrome浏览器中的控制台

如果我像这样将循环中的单词"item"更改为"anotherItem",则

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

周期正常

为什么IE 11无法处理单词"item"

Why IE 11 does not process word 'item'

推荐答案

item在IE中被定义为本机函数,并且可能是只读的,因此不能更改其值是原因.

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.

在Edge之前,Microsoft不喜欢遵守标准,并引入了标准中没有的各种功能. item功能在Edge中不存在.

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.

此外,您尚未声明anotherItem,请尝试以下操作:

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

尝试一下:

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

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

如果未使用var键声明变量,并且您不在严格模式下,则它将被定义为全局变量(这不是您想要的变量).全局变量本质上是全局对象的属性,在Web浏览器的上下文中,该属性将是window对象.

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.

将以下内容添加到JS文件的顶部以启用严格模式,然后您将首先无法犯这些错误,因为会引发异常.

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
})()

这篇关于用于IE11中的循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆