且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Nodejs 属性顺序保证

更新时间:2023-11-13 22:45:46

(尽管在实践中我从未见过以不同顺序迭代对象的情况)以下应该至少在 V8 中给你一个不同的顺序.

(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"

此处

ECMA-262 没有指定枚举顺序.事实上的标准是匹配插入顺序,V8 也这样做,但有一个例外:

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 不保证数组索引的枚举顺序(即属性可以解析为 32 位无符号整数的名称).

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.

虽然上面说没有指定枚举顺序,但那是在创建对象之后.我认为我们可以安全地假设插入顺序应该保持一致,因为任何引擎都没有必要改变插入顺序.

Though the above says the enumeration order is not specified but that is after the object is created. I think we can safely assume that insertion order should remain consistent, as there is no point for any engine to do otherwise and alter the insertion order.

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' }