Array.prototype.sort() 的坑:为什么 [1, 11, 2].sort() 结果是 [1, 11, 2]?
Array.prototype.sort() 的坑:为什么 [1, 11, 2].sort() 结果是 [1, 11, 2]?
// 期望:按数字大小排序
const nums = [1, 11, 2, 22, 3];
nums.sort();
console.log(nums); // [1, 11, 2, 22, 3] ❌ 完全没排序?
// 字符串排序也出问题
const files = ['file1.txt', 'file11.txt', 'file2.txt'];
files.sort();
console.log(files); // ["file1.txt", "file11.txt", "file2.txt"] ❌
正确解法为
// 数字升序
nums.sort((a, b) => a - b); // [1, 2, 3, 11, 22]
// 数字降序
nums.sort((a, b) => b - a); // [22, 11, 3, 2, 1]
// 对象按属性排序
const users = [
{ name: '张三', age: 25 },
{ name: '李四', age: 20 },
{ name: '王五', age: 30 }
];
users.sort((a, b) => a.age - b.age);

浙公网安备 33010602011771号