即使将新值分配给键,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/