[英]for in loop in IE11
IE 11 中的控制台
Chrome 中的控制台
如果我將循環中的單詞“item”更改為“anotherItem”,如下所示
var obj = {
id1: 'item 1',
id2: 'item 2',
id3: 'item 3'
};
for (anotherItem in obj){
console.log(anotherItem);
}
循環運行良好
為什么 IE 11 不處理單詞“item”
item
被定義為 IE 中的本機函數,並且可能是只讀的,因此是您無法更改其值的原因。
在 Edge 之前,微軟不喜歡堅持標准,並引入了各種標准中沒有的功能。 Edge 中不存在item
功能。
另外,你還沒有聲明anotherItem
,試試這個:
嘗試這個:
var obj = {
id1: 'item 1',
id2: 'item 2',
id3: 'item 3'
};
for (var anotherItem in obj){
console.log(anotherItem);
}
如果您沒有使用var
關鍵字聲明變量,並且您不在嚴格模式下,它將被定義為全局變量(這不是您想要的)。 全局變量本質上是全局對象的屬性,在 Web 瀏覽器的上下文中,它是window
對象。
將以下內容添加到您的 JS 文件頂部以啟用嚴格模式,然后您將無法首先犯這些錯誤,因為將拋出異常。
"use strict";
您還可以選擇為特定功能啟用嚴格模式,如下所示:
(function() {
"use strict";
// code here is in strict mode
})()
您可以將此示例用於舊瀏覽器。 祝你好運。
var fruits = ["apple", "orange", "cherry"];
fruits.forEach(myFunction);
function myFunction(item, index) {
document.getElementById("demo").innerHTML += index + ":" + item + "<br>";
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.