sorting - Why is -1 sorted before -Infinity in Javascript? - Stack Overflow

Out of curiosity, what rules apply here exactly?alert([-Infinity, -1, Infinity, 0, 1].sort());Outputs:

Out of curiosity, what rules apply here exactly?

alert([-Infinity, -1, Infinity, 0, 1].sort());

Outputs: -1, -Infinity, 0, 1, Infinity

JSFiddle: /


How is it that -Infinity gets sorted between -1 and 0?

Out of curiosity, what rules apply here exactly?

alert([-Infinity, -1, Infinity, 0, 1].sort());

Outputs: -1, -Infinity, 0, 1, Infinity

JSFiddle: http://jsfiddle/8tVGb/


How is it that -Infinity gets sorted between -1 and 0?

Share Improve this question edited Jul 31, 2013 at 1:43 Maciej A. Czyzewski 1,5291 gold badge13 silver badges24 bronze badges asked Jul 31, 2013 at 1:39 GOTO 0GOTO 0 48.1k25 gold badges139 silver badges164 bronze badges 0
Add a ment  | 

1 Answer 1

Reset to default 13

If you don't use a custom pare function, sort always converts the items to strings and orders them lexicographically. Use

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

See also How to sort an array of integers correctly

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744108278a4558829.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信