Is it acceptable style for Node.js libraries to rely on object key order?

Enumerating the keys of javascript objects replays the keys in the order of insertion:

> for (key in {'z':1,'a':1,'b'}) { console.log(key); }
z
a
b

This is not part of the standard, but is widely implemented (as discussed 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 (ie, a property name that can be parsed as a 32-bit unsigned integer).

Is it acceptable practice to rely on this behavior when constructing Node.js libraries?


Absolutely not! It's not a matter of style so much as a matter of correctness.

If you depend on this "de facto" standard your code might fail on an ECMA-262 5th Ed. compliant interpreter because that spec does not specify the enumeration order. Moreover, the V8 engine might change its behavior in the future, say in the interest of performance, eg


Definitely do not rely on the order of the keys. If the standard doesn't specify an order, then implementations are free to do as they please. Hash tables often underlie objects like these, and you have no way of knowing when one might be used. Javascript has many implementations, and they are all competing to be the fastest. Key order will vary between implementations, if not now, then in the future.


不可以。依赖ECMAScript标准,或者您必须与开发人员讨论是否存在像事件标准这样的人。

链接地址: http://www.djcxy.com/p/72260.html

上一篇: 有没有解决数组中无效八进制数字的问题?

下一篇: Node.js库依赖于对象键序是否可接受的样式?