Object does not keep order, yet can increment property correctly. Why?

时间:2018-06-04 17:33:05

标签: javascript

While I understand that the following structure will not maintain order if iterated upon, I don't understand why the id++ works. I would think that incrementing the id is dependent on a structure that maintains order like an array. How is it smart enough to increment? I can't find the documentation. Please help.

let id = 0;
const cars = {
    "ford": {
        "model": "focus",
        "id": id++
    },
    "honda": {
        "model": "civic",
        "id": id++
    },
    "toyota": {
        "model": "corolla",
        "id": id++
    }
}
console.log(cars);
{ 
    ford: { model: 'focus', id: 0 },
    honda: { model: 'civic', id: 1 },
    toyota: { model: 'corolla', id: 2 } 
}

1 个答案:

答案 0 :(得分:1)

对象文字按照源外观的顺序进行评估,就像其他所有JS代码一样。因此,始终在第二个属性值之前计算第一个属性值的表达式。

这种初始化顺序与稍后可以枚举对象属性的顺序无关,正如您所指出的那样,它不一定相同。