假设我有一个对象,它根据函数的返回值分配属性:
var i = 0;
var f = function() { return ++i; }
var foo = {
a:f(),
b:f(),
c:f()
};
是否保证foo.a为1,foo.b为2,foo.c为3?我知道当你遍历一个对象时,JS 不保证顺序,那么赋值呢?
它在 JS 规范的某处指定了吗?我只是问教育原因。
谢谢。
最佳答案
Standard ECMA-262 (5.1) - Section 11.1.5 - Object Initialiser
The production PropertyNameAndValueList : PropertyNameAndValueList , PropertyAssignment is evaluated as follows:
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.
是的,该命令由标准强制执行。
关于javascript - Javascript 对象属性是否按顺序分配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16200387/