js 实现降序
实现数组降序排列
在JavaScript中,可以使用数组的sort()方法结合比较函数实现降序排列。默认情况下,sort()方法会将元素转换为字符串并按升序排列,因此需要自定义比较逻辑。
基本语法:
array.sort((a, b) => b - a);
示例代码:

const numbers = [5, 2, 9, 1, 5, 6];
numbers.sort((a, b) => b - a);
console.log(numbers); // 输出: [9, 6, 5, 5, 2, 1]
对象数组按属性降序排列
若需对对象数组的某个属性降序排列,需在比较函数中指定属性名。
示例代码:

const items = [
{ name: 'Apple', price: 50 },
{ name: 'Banana', price: 30 },
{ name: 'Orange', price: 40 }
];
items.sort((a, b) => b.price - a.price);
console.log(items);
// 输出: [{name: 'Apple', price: 50}, {name: 'Orange', price: 40}, {name: 'Banana', price: 30}]
字符串数组降序排列
对字符串数组降序排列时,需使用localeCompare()方法或直接比较字符编码。
示例代码:
const fruits = ['apple', 'banana', 'orange'];
fruits.sort((a, b) => b.localeCompare(a));
console.log(fruits); // 输出: ['orange', 'banana', 'apple']
注意事项
sort()方法会直接修改原数组,若需保留原数组,需先创建副本:const sorted = [...array].sort((a, b) => b - a);- 对于大数组,考虑性能优化的排序算法(如快速排序),但原生
sort()在多数场景已足够高效。






