对象属性do具有与插入顺序不同的特定顺序,在这种情况下并不真正有用,如所描述的T.J.克劳德 https://stackoverflow.com/a/42361782/5647260. This https://stackoverflow.com/questions/5525795/does-javascript-guarantee-object-property-orderStack Overflow 问题是关于该主题的好读物,我建议您比第一个答案进一步阅读。
So instead of relying on objects which have no guarantee to order1, use something that does guarantee order. You can use something like a Map https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map, which is similar to an object with key/value pairs, but the pairs are ordered. For example:
const obj = new Map([
["first", "foo"],
["second", "bar"],
["third", undefined],
["fourth", undefined]
]);
const result = Array.from(obj.keys()).reduce((lastKey, currKey) => obj.get(currKey) !== undefined ? currKey : lastKey);
console.log(result);
The Map
构造函数接受一个可迭代对象来创建一个Map
在......之外。数组的数组构造了一个Map
带有子数组的键和值对。因此,以下Map
创建并存储到obj
:
+----------+-----------+
| Key | Value |
+----------+-----------+
| "first" | "foo" |
| "second" | "bar" |
| "third" | undefined |
| "fourth" | undefined |
+----------+-----------+
然后,该行Array.from(obj.keys()) https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from从键创建一个数组Map
哪个是first
, second
, third
, and fourth
。然后它使用Array.prototype.reduce https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce推断出具有定义值的最后一个键。
The reduce
callback uses lastKey
which is the accumulator/last key with the defined value, and currKey
which is the current key being processed. It then checks if obj.get(currKey) https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/get is not undefined. If it is not undefined, then it is returned and assigned to the accumulator. This goes through the entire array and the final value (accumulator) is returned to result
. The result is the last key that had a defined value.2
1It should be noted that in ES2015, there are a selection of methods that do actually guarantee returning the keys in the insertion order. These include Object.assign
, Object.defineProperties
, Object.getOwnPropertyNames
, Object.getOwnPropertySymbols
, and Reflect.ownKeys
. You can rely on these, instead of using Map
.
2There are many other ways to get the last key. You could filter the array and slice it, like Reuven Chacha https://stackoverflow.com/a/42356935/5647260 did. I think reducing it is more descriptive but some other approaches are more straightforward in operation.