Nodejs 属性顺序保证

编程入门 行业动态 更新时间:2024-10-26 14:32:02
本文介绍了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 属性顺序保证

本文发布于:2023-11-06 07:58:27,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1563127.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:顺序   属性   Nodejs

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!