当前位置:首页 > JavaScript

js 实现降序

2026-03-14 13:45:16JavaScript

数组降序排序

使用 sort() 方法结合比较函数实现降序排列:

const numbers = [3, 1, 4, 1, 5, 9];
numbers.sort((a, b) => b - a);
console.log(numbers); // 输出: [9, 5, 4, 3, 1, 1]

对象数组按属性降序

对对象数组中的特定属性进行降序排序:

const items = [
  { name: 'Apple', price: 100 },
  { name: 'Banana', price: 50 },
  { name: 'Orange', price: 120 }
];

items.sort((a, b) => b.price - a.price);
console.log(items);
// 输出:
// [
//   { name: 'Orange', price: 120 },
//   { name: 'Apple', price: 100 },
//   { name: 'Banana', price: 50 }
// ]

字符串降序排序

对字符串数组进行降序排列时需要使用 localeCompare

const fruits = ['apple', 'banana', 'cherry', 'date'];
fruits.sort((a, b) => b.localeCompare(a));
console.log(fruits); // 输出: ['date', 'cherry', 'banana', 'apple']

保持原数组不变的降序排序

创建新数组进行排序而不修改原数组:

const original = [5, 2, 8, 1];
const sorted = [...original].sort((a, b) => b - a);
console.log(original); // [5, 2, 8, 1]
console.log(sorted);   // [8, 5, 2, 1]

大数组高效排序

对于大型数组,考虑使用 TypedArray 提高性能:

js 实现降序

const largeArray = new Int32Array([...Array(1e6).keys()]);
largeArray.sort((a, b) => b - a);

标签: 降序js
分享给朋友:

相关文章

js实现拖拽

js实现拖拽

实现拖拽的基本步骤 使用JavaScript实现拖拽功能需要监听鼠标事件,包括mousedown、mousemove和mouseup。以下是实现的基本逻辑: const draggableEleme…

使用js实现

使用js实现

使用JavaScript实现 JavaScript可以通过Math.random()函数生成随机数,结合其他方法可以实现多种随机数生成需求。 // 生成0到1之间的随机小数 const random…

js 实现跳转

js 实现跳转

使用 window.location.href 进行跳转 通过修改 window.location.href 可以跳转到指定 URL,浏览器会加载新页面: window.location.hre…

js 实现拖拽

js 实现拖拽

实现拖拽的基本步骤 在JavaScript中实现拖拽功能需要监听几个关键事件:mousedown、mousemove和mouseup。以下是实现的基本逻辑。 监听目标元素的mousedown事件,记…

js 实现全屏

js 实现全屏

使用 requestFullscreen 方法 通过调用元素的 requestFullscreen 方法可以实现全屏。该方法兼容现代浏览器,但不同浏览器可能需要前缀。 const element =…

js 实现图片轮播

js 实现图片轮播

基础实现方案 使用HTML、CSS和JavaScript创建一个简单的图片轮播。HTML部分定义轮播容器和图片,CSS负责样式布局,JavaScript处理轮播逻辑。 <div class="…