以下是一个使用JavaScript比较函数按照"next"和"previous"属性排序的示例代码:
var arr = [
{ next: 3, previous: 2 },
{ next: 2, previous: 1 },
{ next: 1, previous: 3 }
];
arr.sort(function(a, b) {
if (a.next < b.next) {
return -1;
}
if (a.next > b.next) {
return 1;
}
// 如果"next"属性相等,则比较"previous"属性
if (a.previous < b.previous) {
return -1;
}
if (a.previous > b.previous) {
return 1;
}
return 0;
});
console.log(arr);
在上述示例中,我们使用sort()
方法对数组arr
进行排序。在比较函数中,首先比较每个对象的"next"属性。如果两个对象的"next"属性不相等,则根据它们的相对值返回-1或1。如果"next"属性相等,则继续比较"previous"属性,使用相同的逻辑返回-1、1或0。
输出结果为:[ { next: 1, previous: 3 }, { next: 2, previous: 1 }, { next: 3, previous: 2 } ]
,表明数组已按照"next"和"previous"属性排序。