gpt4 book ai didi

javascript - Object.entries(),为什么我的数组默认按数字排序?

转载 作者:行者123 更新时间:2023-12-01 15:37:05 28 4
gpt4 key购买 nike

我正在编写一个简单的代码练习解决方案,发现似乎是 object.entries()进行内部数字升序排序。自 docs 以来,我一直希望自己必须对键值对进行排序。说如果你需要一个特定的订单,你必须做一个排序。为什么会发生这种情况,我可以依靠这种行为吗?

/*
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);

最佳答案

Object.entries 使用规范操作 EnumerableOwnPropertyKeys ,它又使用对象的 [[OwnPropertyKeys]],对于大多数对象(包括数组)来说,它是 OrdinaryOwnPropertyKeys .该操作专门针对看起来像数组索引的特殊情况下的属性名称,并按数字顺序列出它们。算法是:

  1. Let keys be a new empty List.
  2. For each own property key P of O such that P is an array index, in ascending numeric index order, do
    1. Add P as the last element of keys.
  3. For each own property key P of O such that Type(P) is String and P is not an array index, in ascending chronological order of property creation, do
    1. Add P as the last element of keys.
  4. For each own property key P of O such that Type(P) is Symbol, in ascending chronological order of property creation, do
    1. Add P as the last element of keys.
  5. Return keys.

关于javascript - Object.entries(),为什么我的数组默认按数字排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63318185/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com