我正在编写一个简单的代码练习解决方案,并遇到了似乎object.entries()在进行内部数字升序排序的内容。我原以为必须自己对键值对进行排序,因为文档说如果您需要特定顺序,则必须进行排序。为什么会发生这种情况,我可以依赖这种行为吗?
/*
Given an input of [1,2,4,591,392,391,2,5,10,2,1,1,1,20,20],
make a function that organizes these into individual array that is ordered.
The above input should return:
[[1,1,1,1],[2,2,2],4,5,10,[20,20],391,392,591].
*/
const cleanTheRoom = (mess) => {
let hash = {};
for (let i = 0; i < mess.length; i++) {
(hash.hasOwnProperty(mess[i])) ? hash[mess[i]]++ : hash[mess[i]] = 1;
}
const clean = [];
for (const [key, value] of Object.entries(hash)) {
(value > 1) ? clean.push(Array(value).fill(key)) : clean.push(key);
}
return clean;
}
let cleaned = cleanTheRoom(
[1,2,4,591,392,391,2,5,10,2,1,1,1,20,20]
);
console.log(cleaned);Run Code Online (Sandbox Code Playgroud)
Object.entries使用规范操作EnumerableOwnPropertyKeys,它反过来使用对象的 [[OwnPropertyKeys]],对于大多数对象(包括数组)来说,它是OrdinaryOwnPropertyKeys。该操作专门用于特殊情况的属性名称,它们看起来像数组索引并按数字顺序列出它们。算法是:
- 让键成为一个新的空列表。
- 对于 O 的每个自己的属性键 P 使得 P 是一个数组索引,按数字索引升序,做
- 添加 P 作为键的最后一个元素。
- 对于 O 的每个自己的属性键 P 使得 Type(P) 是 String 并且 P 不是数组索引,按照属性创建的升序时间顺序,做
- 添加 P 作为键的最后一个元素。
- 对于 O 的每个自己的属性键 P 使得 Type(P) 是 Symbol,按照属性创建的时间顺序,做
- 添加 P 作为键的最后一个元素。
- 返回键。
| 归档时间: |
|
| 查看次数: |
72 次 |
| 最近记录: |