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

Javascript sort array function performance - Stack Overflow

programmeradmin1浏览0评论

Does anyone know how the built-in JS function array.sort() functions internally? I mean does it change strings to numbers....etc

var keys = new Array();
keys.sort();

Does anyone know how the built-in JS function array.sort() functions internally? I mean does it change strings to numbers....etc

var keys = new Array();
keys.sort();
Share Improve this question edited Nov 8, 2011 at 20:27 Felix Kling 818k181 gold badges1.1k silver badges1.2k bronze badges asked Nov 8, 2011 at 20:22 abbasabbas 4323 gold badges10 silver badges22 bronze badges 3
  • 2 btw, new Array is evil, use [] literal syntax instead. – hugomg Commented Nov 8, 2011 at 20:24
  • 6 The algorithm is specified here. Apart from that I'm not sure what else you want to know. – Felix Kling Commented Nov 8, 2011 at 20:25
  • To answer the question: No, .sort will not change any element values, unless you specify a function which modifies the input. eg: keys.sort(function(x,y){x.moo=1337; y.cowsay="bar";}) – Rob W Commented Nov 8, 2011 at 20:30
Add a ment  | 

1 Answer 1

Reset to default 7

From the MDN docs for sort():

If pareFunction is not supplied, elements are sorted by converting them to strings and paring strings in lexicographic ("dictionary" or "telephone book," not numerical) order. For example, "80" es before "9" in lexicographic order, but in a numeric sort 9 es before 80.

Refer to the answers of this question as to what algorithm is being used.

发布评论

评论列表(0)

  1. 暂无评论