// 示例代码:使用 JavaScript 的 sort 方法对数组进行排序
// 定义一个数字数组
let numbers = [1, 5, 10, 2, 8];
// 使用 sort 方法对数组进行升序排序
numbers.sort((a, b) => a - b);
console.log(numbers); // 输出: [1, 2, 5, 8, 10]
// 使用 sort 方法对数组进行降序排序
numbers.sort((a, b) => b - a);
console.log(numbers); // 输出: [10, 8, 5, 2, 1]
// 定义一个字符串数组
let words = ["banana", "apple", "cherry", "date"];
// 使用 sort 方法对字符串数组进行默认排序(按字母顺序)
words.sort();
console.log(words); // 输出: ["apple", "banana", "cherry", "date"]
// 使用 sort 方法对字符串数组进行自定义排序(按字符串长度)
words.sort((a, b) => a.length - b.length);
console.log(words); // 输出: ["date", "apple", "banana", "cherry"]
sort() 方法用于对数组元素进行原地排序,并返回排序后的数组。sort() 方法会将数组元素转换为字符串并按照 Unicode 码点进行排序。因此,对于数字排序,通常需要提供一个比较函数来确保正确排序。(a, b) => a - b 用于升序排序,(a, b) => b - a 用于降序排序。上一篇:js sort排序
下一篇:js string length
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站