为什么JavaScript不能排序[5,10,1]? [英] Why can't JavaScript sort [5, 10, 1]?

查看:53
本文介绍了为什么JavaScript不能排序[5,10,1]?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这似乎是一种简单的排序,但JavaScript却给出了错误的结果。

This seems like a simple sort, yet JavaScript is giving an incorrect result.

我做错了什么或这是一种语言怪癖?

Am I doing something wrong or is this a language quirk?


[5,10,1] .sort();

[5, 10, 1].sort();

[1,10,5 ]

[ 1, 10, 5 ]


推荐答案

Javascript按字母顺序排序。这意味着10低于5,因为1低于5。

Javascript sorts alphabetically. This means that "10" is lower than "5", because "1" is lower than "5".

要对数值进行排序,需要传递数值比较器像这样:

To sort numerical values you need to pass in numerical comparator like this:

function sorter(a, b) {
  if (a < b) return -1;  // any negative number works
  if (a > b) return 1;   // any positive number works
  return 0; // equal values MUST yield zero
}

[1,10, 5].sort(sorter);

或者你可以通过传递更简单的功能作弊:

Or you can cheat by passing simpler function:

function sorter(a, b){
  return a - b;
}

[1, 10, 5].sort(sorter);

这个较短函数的逻辑是比较器必须返回 x> 0如果a > b x< 0如果< b 零,如果a等于b 。所以万一你有

Logic behind this shorter function is that comparator must return x>0 if a > b, x<0 if a < b and zero if a is equal to b. So in case you have

a=1 b=5
a-b will yield negative(-4) number meaning b is larger than a

a=5 b=1
a-b will yield positive number(4) meaning a is larger than b

a=3 b=3
a-b will yield 0 meaning they are equal

这篇关于为什么JavaScript不能排序[5,10,1]?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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