简体   繁体   English

通过自定义函数IE js排序数组不起作用

[英]IE js sorting array by custom function doesn't work

I have simple custom sorting function in js: 我在js中有简单的自定义排序功能:

function compareDesc(a, b) {
    return a.value < b.value;
}

I am then trying to sort an array of dictionaries: 然后我尝试对一组字典进行排序:

var test = [];
test.push({value: 0, foo: "bar"});
test.push({value: 250, foo: "bar"});
test.push({value: 3, foo: "bar"});
test.sort(compareDesc);
alert(test[0].value);
alert(test[1].value);
alert(test[2].value);

It works in Chrome and Firefox where I get: 它适用于Chrome和Firefox,我得到:

250
3
0

But in all version of IE I get: 但在IE的所有版本中,我得到:

0
250
3

So the sorting doesn't work. 所以排序不起作用。 Any ideas why? 有什么想法吗?

It is better to return 1, 0 and -1 instead of just true and false : 最好返回1,0和-1而不是truefalse

function compareDesc(a, b) {
    if (a.value < b.value){
        return 1;
    }
    else if(a.value > b.value)
    {
        return -1;
    }
    return 0;
}

Here is an example: http://jsfiddle.net/2wwBF/2 这是一个例子: http//jsfiddle.net/2wwBF/2

PS The example of the sort function from JS documentation proposes the following way: PS JS文档中的sort函数示例提出了以下方法:

function compareDesc(a, b) {
    return a.value - b.value
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM