Nodejs 属性顺序保证
Nodejs Order of properties guarantee
注意:我使用的 Nodejs 可能与 vanilla ECMAscript 的标准有细微差别,也可能没有。
我一直听说,当使用 for-each 循环遍历对象的属性时,我不应该指望属性的顺序相同。 (尽管在实践中我从未见过对象以不同顺序迭代的情况)。在生产中,我认为我们有一个拼写错误,其中创建的对象被覆盖 属性.
var obj = {
a: 'a property',
b: 'another property',
c: 'yet another property',
a: 'woah we have another a?'
}
在 Nodejs 中,我是否保证包含字符串 'woah we have another a?'
的第二个 属性 会 ALWAYS 隐藏包含字符串的第一个 属性字符串 'a property'
?
(even though in practice I have never seen a case where the objects were iterated over in a different order)
The following should give you a different order in V8 atleast.
var obj = {
"first":"first",
"2":"2",
"34":"34",
"1":"1",
"second":"second"
};
for (var i in obj) { console.log(i); };
// Order listed:
// "1"
// "2"
// "34"
// "first"
// "second"
如讨论的那样here
ECMA-262 does not specify enumeration order. The de facto standard is to match
insertion order, which V8 also does, but with one exception:
V8 gives no guarantees on the enumeration order for array indices (i.e., a property
name that can be parsed as a 32-bit unsigned integer).
Remembering the insertion order for array indices would incur significant memory
overhead.
虽然上面说了没有指定枚举顺序,但那是在创建对象之后。我认为我们可以安全地假设插入顺序应该保持一致,因为任何引擎都没有必要做其他事情并改变插入顺序。
var obj = {
"first":"first",
"2":"2",
"34":"34",
"1":"1",
"second":"second",
2: "two"
};
// gives result
{ '1': '1',
'2': 'two',
'34': '34',
first: 'first',
second: 'second' }
注意:我使用的 Nodejs 可能与 vanilla ECMAscript 的标准有细微差别,也可能没有。
我一直听说,当使用 for-each 循环遍历对象的属性时,我不应该指望属性的顺序相同。 (尽管在实践中我从未见过对象以不同顺序迭代的情况)。在生产中,我认为我们有一个拼写错误,其中创建的对象被覆盖 属性.
var obj = {
a: 'a property',
b: 'another property',
c: 'yet another property',
a: 'woah we have another a?'
}
在 Nodejs 中,我是否保证包含字符串 'woah we have another a?'
的第二个 属性 会 ALWAYS 隐藏包含字符串的第一个 属性字符串 'a property'
?
(even though in practice I have never seen a case where the objects were iterated over in a different order) The following should give you a different order in V8 atleast.
var obj = {
"first":"first",
"2":"2",
"34":"34",
"1":"1",
"second":"second"
};
for (var i in obj) { console.log(i); };
// Order listed:
// "1"
// "2"
// "34"
// "first"
// "second"
如讨论的那样here
ECMA-262 does not specify enumeration order. The de facto standard is to match insertion order, which V8 also does, but with one exception:
V8 gives no guarantees on the enumeration order for array indices (i.e., a property name that can be parsed as a 32-bit unsigned integer).
Remembering the insertion order for array indices would incur significant memory overhead.
虽然上面说了没有指定枚举顺序,但那是在创建对象之后。我认为我们可以安全地假设插入顺序应该保持一致,因为任何引擎都没有必要做其他事情并改变插入顺序。
var obj = {
"first":"first",
"2":"2",
"34":"34",
"1":"1",
"second":"second",
2: "two"
};
// gives result
{ '1': '1',
'2': 'two',
'34': '34',
first: 'first',
second: 'second' }