枚举javascript对象的键会按插入顺序重放键:
> for (key in {'z':1,'a':1,'b'}) { console.log(key); }
z
a
b
这不是标准的一部分,但已被广泛实现(如 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).
在构建 Node.js 库时依赖这种行为是否可以接受?
最佳答案
绝对不是!这不是风格的问题,而是正确性的问题。
如果您依赖这个“事实上的”标准,您的代码可能会在 ECMA-262 第 5 版上失败。兼容的解释器,因为该规范没有指定枚举顺序。此外,V8 引擎可能会在未来改变其行为,例如为了性能,例如
关于javascript - Node.js 库依赖对象键顺序是否可以接受?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9179680/