node.js - Nodejs 属性顺序保证

标签 node.js properties

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

我一直听说,当使用 for-each 循环迭代对象的属性时,我不应该指望属性具有相同的顺序。 (尽管在实践中我从未见过以不同顺序迭代对象的情况)。在生产中,我们发现了一个拼写错误,即使用覆盖的属性创建了对象。

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

在 Nodejs 中,我是否保证第二个包含字符串 'woah we had another a?' 的属性将始终隐藏第一个包含字符串 “属性”

最佳答案

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

关于node.js - Nodejs 属性顺序保证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30927089/

相关文章:

node.js - socket.io 客户端未接收

java初学者-我应该在哪个文件夹中放置 "database.properties"文件

node.js - NodeJS https是否对流量进行对称加密

node.js - Node.js 中的 Hello World

Spring - 从 JNDI 设置属性值

spring 属性注入(inject)不起作用 @Value 和 <util :properties>

c# - 如何获取类的属性列表?

java - 如何管理不同应用实例的属性文件?

node.js - gulp.series 不序列化任务

node.js - Node Inspector 在 Ubuntu 上安装失败