寫一個自定義的數組排序,可以自己制定數組的排序規則: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-s ...
寫一個自定義的數組排序,可以自己制定數組的排序規則:
<!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>index.html
結果展示: