Safari不像其他浏览器那样对对象数组进行排序 [英] Safari doesn't sort array of objects like others browsers

查看:75
本文介绍了Safari不像其他浏览器那样对对象数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

var myArray = [{date:"2013.03.01"},{date:"2013.03.08"},{date:"2013.03.19"}];

我试过:

function(a,b){
  return b.date > a.date;
}

function(a,b){
  return b.date - a.date;
}

Chrome和Firefox 中的console.log我想要的输出:

The console.log in Chrome and Firefox give me the desired output:

"2013.03.19", "2013.03.08", "2013.03.01"

Safari 给出原始排序:

"2013.03.01", "2013.03.08", "2013.03.19"

为什么?

推荐答案

JavaScript中的排序函数应该返回一个实数 - 不是真或假,或是字符串或日期。该数字是正数,负数还是零会影响排序结果。

A sort function in JavaScript is supposed to return a real number -- not true or false or a string or date. Whether that number is positive, negative, or zero affects the sort result.

尝试此排序函数(它还将正确排序任何字符串反向字母顺序):

Try this sort function (which will also correctly sort any strings in reverse-alphabetical order):

myArray.sort(function(a,b){
  return (b.date > a.date) ? 1 : (b.date < a.date) ? -1 : 0;
});

这篇关于Safari不像其他浏览器那样对对象数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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