// 对普通数组进行排序
let nums = [1, 3, 4, -4, 2, 5, 1];
nums.sort(function (a, b) {
// 升序
// return a - b;
//降序
return b - a;
});
console.log(nums);
// 对字符串数组进行排序
let arr = ["asd", "as", "a", "asdf"];
arr.sort(function (str1, str2) {
// 升序
// return str1.length - str2.length;
//降序
return str2.length - str1.length;
});
console.log(arr);
// 对对象数组进行排序
let students = [
{name: "zs", age: 12},
{name: "ls", age: 7},
{name: "ww", age: 30},
{name: "zl", age: 10},
];
students.sort(function (stu1, stu2) {
// return stu1.age - stu2.age;
return stu2.age - stu1.age;
});
console.log(students);
JavaScript数组的sort方法常规用法
最新推荐文章于 2024-05-04 23:19:14 发布