JS如何排序没有比较函数的对象数组?



根据标题,JS如何在不使用比较函数的情况下排序对象数组?

例如:

const bookshops = [{
id: 3,
name: 'bookshop3',
imgSrc: 'https://www.google.com/'
}, {
id: 8,
name: 'bookshop8',
imgSrc: 'https://www.google.com/'
}, {
id: 2,
name: 'bookshop2',
imgSrc: 'https://www.google.com/'
}, {
id: 9,
name: 'bookshop9',
imgSrc: 'https://www.google.com/'
}, {
id: 4,
name: 'bookshop4',
imgSrc: 'https://www.google.com/'
}, {
id: 6,
name: 'bookshop6',
imgSrc: 'https://www.google.com/'
}, {
id: 10,
name: 'bookshop10',
imgSrc: 'https://www.google.com/'
}, {
id: 7,
name: 'bookshop7',
imgSrc: 'https://www.google.com/'
}];
bookshops.sort();
console.log(bookshops);

输出是什么?做"bookshops"得到排序?

特别感谢@VLAZ &@Hassan Imam给我看了答案。

为了让任何来查看这个问题的人更清楚:

Javascript排序比较函数是按字典排序的。这意味着如果你不传递比较函数:

xxx.sort()

排序将比较数组中每个值的字典顺序值。

根据这里的规格:

如果没有提供compareFunction,所有未定义的数组元素通过将它们转换为字符串并按UTF-16代码单位顺序比较字符串来排序。例如,"香蕉";在"樱桃"之前。在数字排序中,9在80之前,但由于数字被转换为字符串,所以"80";出现在"9"按Unicode顺序。所有未定义的元素排序到数组末尾。

进一步说明:

const list = [80, 9];
list.sort();
console.log(list); // [80, 9] <= its not [9, 80]

总之,总是使用比较函数

最新更新