在对象上使用Object.values()之后,数组元素的顺序是否可以更改?

时间:2018-04-13 13:20:15

标签: javascript

我有一个这样的对象:

object = {
  1483295400000: {label: "Jan 02 to 08", total: 8062, billings: Array(4)},
  1483900200000: {label: "Jan 09 to 15", total: 9940, billings: Array(8)},
  1484505000000: {label: "Jan 16 to 22", total: 7901, billings: Array(5)},
  1485109800000: {label: "Jan 23 to 29", total: 4652, billings: Array(3)},
  1485714600000: {label: "Jan 30 to 05", total: 3952, billings: Array(2)}
}

当我使用Object.values(object)时,我得到了一个这样的数组:

[
  { label: "Jan 23 to 29", total: 4652, billings: Array(3) },
  { label: "Jan 16 to 22", total: 7901, billings: Array(5) },
  { label: "Jan 02 to 08", total: 8062, billings: Array(4) },
  { label: "Jan 09 to 15", total: 9940, billings: Array(8) },
  { label: "Jan 30 to 05", total: 3952, billings: Array(2) }
]

为什么数组中对象的顺序发生了变化,原因是什么?

1 个答案:

答案 0 :(得分:3)

根据Dr. Axel Rauschmayer's article - The traversal order of object properties in ES6,travesral的顺序是:

  • 首先,作为整数索引的键(后面会说明这些键),按升序排列。
  • 然后,所有其他字符串键,按照它们添加到对象的顺序。
  • 最后,所有符号键按照添加到对象的顺序。

演示:

const obj = { b: 'key1', 3: 'c', 1: 'a', 2: 'b', a: 'key2' };

console.log(Object.values(obj)); // a, b, c - values of numerical keys, key1 and key2 - string keys in order of appearance in original object