写一个自定义的数组排序,可以自己制定数组的排序规则:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <script> // 数组通用排序 // arr:一个数组;compare:自定义比较函数 function arraySort(arr, compare) { // 冒泡排序,升序 for (var i = 1; i < arr.length; i++) { for (var j = 0; j < (arr.length - i); j++) { if (compare(arr[j], arr[j + 1]) > 0) {//第一个比第二个值大,则交换位置 var temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } } var arr = [ {name:"张三",age:19}, {name:"李四",age:18}, {name:"王五",age:21}, {name:"赵六",age:20} ]; //比较数组中的年龄 arraySort(arr, function(a, b){ return a.age - b.age; }); console.log(arr); </script> </body> </html>
结果展示: