We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
JS中的sort函数是可以接收排序方法作为参数的,所以我们就利用这点来进行自定义排序。
const array = [1, 5, 2, 4, 3]; array.sort();
const array = [1, 5, 2, 4, 3]; function compare(a, b) { return b - a; } array.sort(compare);
将下面的对象根据年龄进行排序:
const friends = [ { name: 'John', age: 30 }, { name: 'Ana', age: 20 }, { name: 'Tom', age: 25 }, ]; function comparePerson(a, b) { return a.age - b.age; } friends.sort(comparePerson);
const names = ['Ana', 'ana', 'john', 'John']; names.sort();
上面的代码得到的结果是 ["Ana", "John", "ana", "john"],这是因为js在做字符比较的时候是根据字符对应的ASCII值来进行比较的,如:A, J, a, j 对应的ASCII值分别是 65, 75, 97, 106。
["Ana", "John", "ana", "john"]
想要得到我们想要的 ["Ana", "ana", "John", "john"],只需要给sort传入一个忽略大小写的比较函数即可:
["Ana", "ana", "John", "john"]
function stringCompare(a, b) { if (a.toLowerCase() < b.toLowerCase()) { return -1; } if (a.toLowerCase() > b.toLowerCase()) { return 1; } return 0; } names.sort(stringCompare);
The text was updated successfully, but these errors were encountered:
function compare(a, b) { return a - b; }
这样写省事多了
Sorry, something went wrong.
@junnplus get 🌹
最近写前端用lodash感觉很舒服。。。
@junnplus 全栈大佬
ttop5
No branches or pull requests
JS中的sort函数是可以接收排序方法作为参数的,所以我们就利用这点来进行自定义排序。
1. 数组升序
2. 数组降序
3. 对象数组
将下面的对象根据年龄进行排序:
4. 字符串数组
上面的代码得到的结果是
["Ana", "John", "ana", "john"]
,这是因为js在做字符比较的时候是根据字符对应的ASCII值来进行比较的,如:A, J, a, j 对应的ASCII值分别是 65, 75, 97, 106。想要得到我们想要的
["Ana", "ana", "John", "john"]
,只需要给sort传入一个忽略大小写的比较函数即可:The text was updated successfully, but these errors were encountered: