Order of Elements in a "for (… in …)" Loop
In JavaScript, "for...in" loops iteratein" loops iteratein" through the enumerable properties of an object. While these properties are generally accessed in the order in which they were defined, it's important to note that this behavior is implementation-dependent.
According to John Resig, the author of jQuery, all major browsers current except for a few cases in Chrome. However, the ECMAScript specification explicitly states that this behavior is undefined.
In實務中,所有現代的 ECMAScript 實作都會依定義順序迭代物件屬性。值得注意的是,Chrome 和 Opera 是例外,它們為每個非數字屬性名稱執行此操作。這兩個瀏覽器按順序拉入屬性,領先於第一個非數字屬性(這與它們實現數組的方式有關)。 Object.keys 也遵循相同的順序。
以下範例清楚地說明了發生的情況:
var obj = { "first": "first", "2": "2", "34": "34", "1": "1", "second": "second" }; for (var i in obj) { console.log(i); };
輸出順序:
重要的是要注意,這種行為隨時可能改變。因此,不建議依賴當前的順序。
結論: 如果順序對您很重要,請使用陣列。
以上是JavaScript 的「for...in」循環順序是否有保證,您應該依賴它嗎?的詳細內容。更多資訊請關注PHP中文網其他相關文章!