javascript - JS 对象键序列

标签 javascript

即使将新值分配给键,javascript 是否保证对象的键序列得到保留?

例如,如果我有以下对象

var Object = {
    keyX: value1,
    keyB: value2,
    keyZ: value3
}

如果我使用 for .. in 遍历键,我会得到正确的序列,即 keyX、keyB、keyZ。如果我更改 keyB 的值,我仍然会在迭代中得到相同的序列。

我的问题是,序列会始终保持不变,还是随时可能发生变化?

最佳答案

好吧,文档中说得很清楚 ( MDN ):

A for...in loop iterates over the properties of an object in an arbitrary order.

this section文档对此给出了更全面的解释:

Although ECMAScript makes iteration order of objects implementation-dependent, it may appear that all major browsers support an iteration order based on the earliest added property coming first (at least for properties not on the prototype). However, in the case of Internet Explorer, when one uses delete on a property, some confusing behavior results, preventing other browsers from using simple objects like object literals as ordered associative arrays.

In Explorer, while the property value is indeed set to undefined, if one later adds back a property with the same name, the property will be iterated in its old position--not at the end of the iteration sequence as one might expect after having deleted the property and then added it back.

关于javascript - JS 对象键序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12388412/

相关文章:

javascript - 在javascript中定位最接近的类

javascript - 创建一个循环来计算平均分

javascript - Google 饼图 - 图像作为标签

javascript - 单击后在 html 中的三个图标之间切换

javascript - JQuery 事件在动态内容中重复

javascript - 使用 JavaScript 的增值税计算器

javascript - Firebase 函数 :Function returned undefined, 预期的 promise 或值(value)

javascript - 如何检测右键单击+左键单击

javascript - 使用 php 将登录用户从登录页面重定向到用户仪表板

javascript - 通过 Kinetic.js 文本元素中的字符串索引获取单词/字符屏幕位置