for in 循環的輸出順序問題


 
           var data = {
                '4': 'first',
                '3': 'second',
                '2': 'third',
                '1': 'fourth'
            };
            for (var i in data) {
                console.log(i + "  " + data[i])
            }

IE11, chrome31, firefox23的打印如下:

 
1  fourth
2  third
3  second
4  first
 

var obj = {
  "first":"first",
   "zoo":"zoo",
  "2":"2",
  "34":"34",
  "1":"1",
  "second":"second"
};
for (var i in obj) { console.log(i); };

IE11, chrome31, firefox23的打印如下:

 

1
2
34
first
zoo
second

根據stackoverflow給出的答案

Currently all major browsers loop over the properties of an object in the order in which they were defined. Chrome does this as well, except for a couple cases. [...] This behavior is explicitly left undefined by the ECMAScript specification. In ECMA-262, section 12.6.4:
The mechanics of enumerating the properties ... is implementation dependent.
However, specification is quite different from implementation. All modern implementations of ECMAScript iterate through object properties in the order in which they were defined. Because of this the Chrome team has deemed this to be a bug and will be fixing it.
All browsers respect definition order with the exception of Chrome and Opera which do for every non-numerical property name. In these two browsers the properties are pulled in-order ahead of the first non-numerical property (this is has to do with how they implement arrays). The order is the same for Object.keys as well.

事實上,它不一定根據定義時的順數輸出,所有瀏覽器的最新版本現在都按chrome執行,先把當中的非負整數鍵提出來,排序好輸出,然后將剩下的定義時的順序輸出。由於這個奇葩的設定,讓avalon的ms-with對象排序不按預期輸出了。只能強制用戶不要以純數字定義鍵名:

 

var obj = {
  "first":"first",
   "zoo":"zoo",
  "2a":"2",
  "34u":"34",
  "1l":"1",
  "second":"second"
};
for (var i in obj) { console.log(i+" "+obj[i]); };

IE11, chrome31, firefox23的打印如下:

 
first first
zoo zoo
2a 2
34u 34
1l 1
second second


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM