javascript sort() 方法默认按字母顺序排列数组元素,并将它们视为字符串。数值排序需要自定义比较函数,让您可以控制排序标准,实现精准高效的整理。
语法:
arr.sort(comparefunction);
参数:
- array:要排序的数组。
- comparefunction (可选):定义排序顺序的函数。如果省略,数组元素将根据其字符串 unicode 代码点进行排序。
示例 1:对字符串数组进行排序
// original array let arr = ["ganesh", "ajay", "kunal"]; console.log(arr); // output:["ganesh", "ajay", "kunal"] // sorting the array console.log(arr.sort()); // output: [ 'ajay', 'ganesh', 'kunal' ]
示例 2:对数字数组进行排序
// original array let numbers = [40, 30, 12, 25]; console.log(numbers); // output: [40, 30, 12, 25] // sorting the array numbers.sort((a, b) => a - b); console.log(numbers); // output: [ 12, 25, 30, 40 ]
冒泡排序实现

除了使用内置的 sort() 方法之外,您还可以实现自己的排序算法。这是使用冒泡排序算法的示例:
立即学习“Java免费学习笔记(深入)”;
index.js
function Sortarr() {
let Data = [40, 30, 12, 25];
for (let i = 0; i < Data.length; i++) {
for (let j = 0; j < Data.length - 1; j++) {
if (Data[j] > Data[j + 1]) {
let temp = Data[j];
Data[j] = Data[j + 1];
Data[j + 1] = temp;
}
}
}
console.log(Data); // Output: [ 12, 25, 30, 40 ]
}
Sortarr();
此冒泡排序实现演示了一种基本排序技术,该技术重复遍历列表、比较相邻元素,如果顺序错误则交换它们。










