javascript array.sort() 在带有 compareFunction 的 IE 11 中不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27123272/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 06:58:50  来源:igfitidea点击:

array.sort() does not work in IE 11 with compareFunction

javascriptinternet-explorersortinginternet-explorer-11plunker

提问by Mario Levrero

I'm sorting an array following JavaScript Array sort() Method. When I use a compareFunctionparameter, Internet Explorer 11 is not sorting properly.

我正在按照JavaScript Array sort() Method 对数组进行排序。当我使用compareFunction参数时,Internet Explorer 11 没有正确排序。

I have a team array with players. These players have names:

我有一个带玩家的团队阵列。这些球员的名字是:

var team = [
  {name:"Waldo"}, 
  {name:"Sarah"}
  ];

But I want to display them at the stadium video board sort by alphabetical order. So I have a list to append them when the DOM is ready:

但我想在体育场视频板上按字母顺序显示它们。所以当 DOM 准备好时,我有一个列表来附加它们:

MyHtml

我的HTML

<h2>My Team after sorting</h2>
      <button onclick='sortAndDisplay()'>Click here to sort by Name</button>
      <ul id="myTeamAfter">

      </ul>

My Javascript code

我的 JavaScript 代码

function sortAndDisplay(){
  $("#myTeamAfter").empty();
  team.sort(function(a, b){return a.name > b.name;});
  for(var i=0; i < team.length; i++){
    $("#myTeamAfter").append( "<li>" + team[i].name + "</li>" );
  }
}

Problem is that some Clubs use Internet Explorer 11 at their stadiums, and sort() function when I use my own compareFunctionis not working properly on IE11, so Waldo is displayed first than Sarah and the fans are confused.

问题是一些俱乐部在他们的体育场馆使用Internet Explorer 11,而我自己使用的sort()函数compareFunction在IE11上无法正常工作,所以Waldo比Sarah先显示,粉丝们很困惑。

I've created a Plunkerwhere you can reproduce it:

我创建了一个Plunker,您可以在其中重现它:

  • Firefox 33.1 - Working!! :)
  • Chrome 39.0.2171.65 - Working!! :)
  • Internet Explorer 11.0.9600 - Not Working :(
  • Firefox 33.1 - 工作!:)
  • Chrome 39.0.2171.65 - 工作!:)
  • Internet Explorer 11.0.9600 - 不工作:(

Any idea to resolve the sort() for every browser?

知道为每个浏览器解决 sort() 吗?

Thanks!

谢谢!

回答by Kos

Your comparer looks incorrect:

您的比较器看起来不正确:

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

This returns trueor false, while it should return -1, 0or 1depending on the ordering.

这将返回trueor false,而它应该返回-1, 0or1取决于排序。

See How to sort strings in JavaScript(specifically localeCompare).

请参阅如何在 JavaScript 中对字符串进行排序(特别是localeCompare)。

So code should be:

所以代码应该是:

function sortAndDisplay() {
  $("#myTeamAfter").empty();
  team.sort(function(a, b) {
    if (a.name < b.name) return -1;
    if (a.name > b.name) return 1;
    return 0;
  });
  for (let i = 0; i < team.length; i++) {
    $("#myTeamAfter").append("<li>" + team[i].name + "</li>");
  }
}