Nodejs 属性顺序保证 [英] Nodejs Order of properties guarantee

查看:51
本文介绍了Nodejs 属性顺序保证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

注意:我使用的 Nodejs 可能与普通 ECMAscript 的标准有细微差别,也可能没有.

Note: I am using Nodejs which may or may not have subtle differences from vanilla ECMAscript's standards.

我一直听说,当使用 for-each 循环遍历对象的属性时,我不应该指望这些属性的顺序相同.(尽管在实践中我从未见过以不同顺序迭代对象的情况).在生产中,我们有一个我认为是一个错字,其中一个对象是用覆盖的属性创建的.

I have always heard that when using a for-each loop to iterate over the properties of an object, I should not count on the properties being in the same order. (even though in practice I have never seen a case where the objects were iterated over in a different order). In production, we have what I believe to be a typo where an object is created with an overwritten property.

var obj = {
  a: 'a property',
  b: 'another property',
  c: 'yet another property',
  a: 'woah we have another a?'
}

在 Nodejs 中,我能保证第二个包含字符串 'woah we have another a?' 的属性会总是隐藏包含字符串 <的第一个属性代码>'属性'?

In Nodejs, am I guaranteed that the second a property containing the string 'woah we have another a?' will ALWAYS shadow the first a property containing the string 'a property'?

推荐答案

(尽管在实践中我从未见过以不同顺序迭代对象的情况)以下应该至少在 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' }

这篇关于Nodejs 属性顺序保证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆