最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin10浏览0评论

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

发布评论

评论列表(0)

  1. 暂无评论