代码如下:
var friends = [
{name: 'John', age: 30},
{name: 'Ana', age: 20},
{name: 'Chris', age: 25}
];
function comparePerson(a, b){
if (a.age < b.age){
return -1
}
if (a.age > b.age){
return 1
}
return 0;
}
console.log(friends.sort(comparePerson));
结果如下:

这篇博客介绍了如何使用JavaScript对数组进行排序,展示了一个名为`comparePerson`的比较函数,该函数根据年龄对人物对象进行升序排序。通过调用`friends.sort(comparePerson)`,数组`friends`中的对象按年龄从小到大排列。

被折叠的 条评论
为什么被折叠?



