Javascript对象属性是按顺序分配的吗?

jdw*_*jdw 17 javascript

假设我有一个对象根据函数的返回值分配属性:

var i = 0;

var f = function() { return ++i; }

var foo = {
            a:f(),
            b:f(),
            c:f()
          };
Run Code Online (Sandbox Code Playgroud)

是否保证foo.a为1,foo.b为2,foo.c为3?我知道当你迭代一个对象时JS不保证顺序,那么赋值呢?

它是在JS规范中指定的吗?我只是出于教育原因.

谢谢.

Kar*_*ath 16

标准ECMA-262(5.1) - 第11.1.5节 - 对象初始化器

生产PropertyNameAndValueList:PropertyNameAndValueList,PropertyAssignment的计算方法如下:

1. Let obj be the result of evaluating PropertyNameAndValueList.
2. Let propId be the result of evaluating PropertyAssignment.
...
5. Call the [[DefineOwnProperty]] internal method of obj with arguments propId.name, propId.descriptor, and false.
6. Return obj.
Run Code Online (Sandbox Code Playgroud)

所以是的,订单是由标准强制执行的.