英文:
custom sort function behaves differently for string vs number keys
问题
根据各种在线资源的帮助,我编写了一个自定义排序函数。当要排序的对象具有字符串键时,它可以正常工作。然而,当对象的键是数字时,它不会按降序排序。
为什么当对象的键是数字时,降序排序不被执行?
英文:
With help from various online sources I put together a custom sorting function. It works properly when the object to be sorted has string keys. However, it does not sort descending when the object keys are numeric.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const sortObjectByKey = (obj, direction = 'asc') => {
const keys = Object.keys(obj).sort();
if (direction == 'desc') keys.reverse();
// return keys;
const sortedObject = {};
for (value of keys) {
sortedObject[value] = obj[value];
}
return sortedObject;
}
const y = { 'zebra': 'runs', 'anteater': 'eats', 'kangaroo': 'hops', 'bovine': 'moos' };
console.log(sortObjectByKey(y));
console.log(sortObjectByKey(y, 'desc'));
const x = { 2021: 'twenty one', 2020: 'twenty', 2019: 'nineteen', 2023: 'twenty three', 2022: 'twenty two', 2018: 'eighteen' };
console.log(sortObjectByKey(x));
console.log(sortObjectByKey(x, 'desc'));
<!-- end snippet -->
Why is descending sort not being honored when the object keys are numeric?
答案1
得分: 0
Object traversal order is:
> 根据现代 ECMAScript 规范,对象遍历顺序是明确定义的,并且在各种实现中保持一致。在原型链的每个组件内,所有非负整数键(即可以作为数组索引的键)将按升序按值进行遍历,然后按属性创建的升序按字符串键的时间顺序遍历。
来源:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in
因此,在遍历过程中将不会尊重数字键的自定义顺序。
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
console.log({2:'two', 1:'one'})
// 输出结果是 {1:'one', 2:'two'} 而不是 {2:'two', 1:'one'}
<!-- end snippet -->
英文:
Object traversal order is:
> The traversal order, as of modern ECMAScript specification, is
> well-defined and consistent across implementations. Within each
> component of the prototype chain, all non-negative integer keys (those
> that can be array indices) will be traversed first in ascending order
> by value, then other string keys in ascending chronological order of
> property creation
Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in
Therefore, a custom ordering of numeric keys will not be respected during traversal.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
console.log({2:'two', 1:'one'})
// prints {1:'one', 2:'two'} instead of {2:'two', 1:'one'}
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论