Microsoft Edge array.sort(compareFunction)无法正确排序 [英] Microsoft Edge array.sort(compareFunction) not sorting correctly

查看:152
本文介绍了Microsoft Edge array.sort(compareFunction)无法正确排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Microsoft Edge版本:41.16299.402.0

Microsoft Edge Version: 41.16299.402.0

我注意到Edge的一个奇怪之处在于,使用array.sort()提供匿名函数似乎无法正确地对我的对象数组进行排序.我的功能可以在Firefox和Chrome中运行.下面的代码作为我遇到的问题的示例:

I've noticed an oddity with Edge in that providing an anonymous function with array.sort() doesn't appear to sort my array of objects correctly. My function works in Firefox and Chrome though. The code below serves as an example of the issue I'm running into:

data = [
    {title: "First", language: "English"}, 
    {title: "Second", language: "Armenian"},
    {title: "Third", language: "Cantonese"}
];

data.forEach(function(val){
    console.log(val);
});

data.sort(function(a,b) { console.log(a.language > b.language); return a.language > b.language;});

data.forEach(function(val){
    console.log(val);
});

如果您在Chrome或Firefox中的JSFiddle中运行该代码,则会注意到第二组控制台日志是按语言按字母顺序排序的.但是在Edge中运行它,两组之间没有任何区别.我假设这与我处理sort()的方式有关,而不是与Edge中的错误有关(似乎是早就可以解决的问题).有人知道我的排序语法有什么问题吗?

If you run that code in JSFiddle in Chrome or Firefox, you'll notice that the second set of console logs is sorted alphabetically by language. Run it in Edge however and there won't be any difference between the two sets. I'm assuming that this has to do with how I am handling sort() and not a bug in Edge (seems like something that would have been fixed a long time ago if that were the case). Does anyone know what's wrong with my sort syntax?

来自 Chrome 的控制台日志的屏幕截图:

Screenshot of console log from Chrome:

来自 Edge 的控制台日志的屏幕截图:

Screenshot of console log from Edge:

推荐答案

问题是,您返回的比较值是truefalse,它被解释为1的数值和0.基本上,它会丢失-1的值,这对于返回成功的排序是必需的.

The problem is, you return the value of a comparison, which is either true or false, which is interpreted as numerical value of 1 and 0. Basically it misses the value of -1 which is necessary to return a sucessfull sorting.

var data = [{ title: "First", language: "English" }, { title: "Second", language: "Armenian" }, { title: "Third", language: "Cantonese" }];

data.sort(function(a, b) { 
    return a.language > b.language || -(a.language < b.language);
});

console.log(data);

仅出于完整性考虑,对于字符串,您可以使用

Just for completeness, for strings, you could use String#localeCompare which has some more features, like natural sorting, or localized possiblities.

var data = [{ title: "First", language: "English" }, { title: "Second", language: "Armenian" }, { title: "Third", language: "Cantonese" }];

data.sort(function(a, b) { 
    return a.language.localeCompare(b.language);
});

console.log(data);

这篇关于Microsoft Edge array.sort(compareFunction)无法正确排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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