JavaScript排序比较器功能 [英] JavaScript sort comparator function

查看:65
本文介绍了JavaScript排序比较器功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上我想构建一个函数,它通过对象的属性/成员变量之一对数组中的对象进行排序。我首先确定比较器函数是隐藏错误的地方,但我不是100%肯定。

Basically I want to build a function which sorts objects in an array by one of the object's properties/member variables. I am preeeety sure that the comparator function is where the error is hidden, but I am not 100% sure.

调用sort函数后我应该得到的输出是 1,2,3 。我得到 1,3,2 这意味着它没有变化

The output I should get after the sort function is called is 1,2,3. I get 1,3,2 which means that it is unchanged

这是整个js代码(有一些评论):

This is the entire js code (with some comments):

var arr = [];
//object definition and creation
var main = document.getElementById("main");
var task = {
    name: "",
    priority: 0
};

//first
var one = Object.create(task);
one.priority = 1;
//secondd
var two = Object.create(task)
two.priority = 3;
//last
var three = Object.create(task);
three.priority = 2;

//append
arr.push(one);
arr.push(two);
arr.push(three);

//sort function
function sortT() {
    arr.sort(compareFN);
}

//comperator function
function compareFN() {
    return task.priority < task.priority;
}

function print() {
    for (var i = 0; i < arr.length; i++) {
        console.log(arr[i].priority);   
    }
}

//execution of the program
print();
sortT();
print();

编辑:解决方案如下 - 如上所述,比较器功能确实是问题,正确写它的方法如下:

The solution is the following - As stated, the comparator function really was the problem, the correct way to write it is the following:

function compareFN(taskA, taskB) {
   return taskA.priority < taskB.priority;
}


推荐答案

compare函数需要两个参数:它应该比较的第一个和第二个元素。
所以你的compareFN应该是这样的:

The compare function needs two arguments: the first and the second element it should compare. So your compareFN should look like this:

function compareFN(taskA, taskB) {
   return taskA.priority - taskB.priority;
}

编辑:正如NPE所说,它应该执行三向比较,所以一个简单的 a< b 在这里不是一个好主意。

As NPE said, it is supposed to perform a three-way comparison, so a simple a < b is not so a great idea here.

这篇关于JavaScript排序比较器功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆