确实是chrome和ie的数组排序错误吗? [英] Is it really a array sorting bug of chrome and ie?

查看:76
本文介绍了确实是chrome和ie的数组排序错误吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个非常简单的数组排序脚本,它可以在Firefox上运行,但是chrome和IE给了我一个无序的数组.

I create a very simple array sorting script, it works on Firefox, but chrome and ie are giving me an unordered array.

var arr = ["2017-02-17",
"2017-02-17",
"2017-02-16",
"2017-02-15",
"2017-02-16",
"2017-02-15",
"2017-02-14",
"2017-02-16",
"2017-02-17",
"2017-02-17",
"2017-02-13"];
arr.sort(function(a, b) {return a>b;});
console.log(arr);

是Chrome/ie错误还是我错过了某些东西?我几乎不相信chrome和具有不同的js引擎存在相同的问题.

Is is a chrome/ie bug or I missed something? I hardly believe that chrome and ie have differenrt js engine have the same issue.

推荐答案

您可以对

You might use the right comparison for Array#sort and use it as return value, instead of a single true/false, which does eliminate the negative value, which is needed.

虽然您有 ISO 6801 日期字符串,但是可以使用

While you have ISO 6801 date strings, you could use String#localeCompare for it.

var arr = ["2017-02-17", "2017-02-17", "2017-02-16", "2017-02-15", "2017-02-16", "2017-02-15", "2017-02-14", "2017-02-16", "2017-02-17", "2017-02-17", "2017-02-13"];

arr.sort(function(a, b) {
    return a.localeCompare(b);
});
console.log(arr);

如果您不关心 Unicode代码点,则可以使用

And if you do not care about Unicode code points, you could use Array#sort

sort()方法在适当的位置对数组的元素进行排序并返回该数组.排序不一定是稳定的.默认的排序顺序是根据字符串Unicode代码点确定的.

The sort() method sorts the elements of an array in place and returns the array. The sort is not necessarily stable. The default sort order is according to string Unicode code points.

没有 compareFunction

var arr = ["2017-02-17", "2017-02-17", "2017-02-16", "2017-02-15", "2017-02-16", "2017-02-15", "2017-02-14", "2017-02-16", "2017-02-17", "2017-02-17", "2017-02-13"];

arr.sort();
console.log(arr);

这篇关于确实是chrome和ie的数组排序错误吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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