Order of Elements in a "for (… in …)" Loop
In JavaScript, "for...in" loops iterate 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 currently loop over object properties in definition order, 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中文网其他相关文章!