编程小贴士

给你的编程提供小点子


javascript数组排序的问题

看看下面的代码,你觉得输出是什么呢?

1
2
3
var a = [30,2,1,9,15];  
a.sort();  
alert(a);

如果你觉得输出是1,2,9,15,30,那就错了,真正的结果是1,15,2,30,9。不过,在没真正搞清楚javascript的数组排序之前还是先别放弃这个强大的语言。

那么这是怎么回事呢?当排序的方法没有参数的时候,所有的值都会被转化成为字符串,然后根据字典顺序排序。所以15会排在2前面,10和19999也一样。

为了解决这个问题,我们需要给sort()方法传递一个比较函数,这个函数需要两个参数,我们暂且命名为a和b,然后返回:

  • 如果a
  • 如果a>b,那么返回一个正数。
  • 如果a=b,就返回0。

最简单的数字比较的函数如下:

1
2
3
function compare(a,b){
    return a-b;
}

我们可以直接把比较函数写在sort里面作为参数传入:

1
2
3
var a = [30,2,1,9,15];  
a.sort(function(a,b) { return a-b; });  
alert(a);

现在的结果就是1,2,9,15,30了

排序函数另外一个强大的地方在于,他可以比较任何类型的对象的任何属性。我们看看下面的例子:

1
2
3
4
5
6
7
8
// location co-ordinates  
var locations = [  
    { name: "shops", x:3, y:4 },  
    { name: "library", x:5, y:3 },  
    { name: "pub", x:1, y:2 }  
];  
// home co-ordinates  
var home = { name: "home", x:0, y:0 };

然后我们定义一个公式来比较:

1
2
3
function distance(p1,p2){
return Math.sqrt(Math.pow(p1.x-p2.x,2)+Math.pow(p1.y-p2.y,2)); 
}

现在我们就可以根据离家距离来排序了。

1
2
3
4
5
6
locations.sort(  
    function(a, b) {  
        return distance(home,a)-distance(home,b);  
    }  
);  
// locations sorted: pub, shops, library

或者也可以由远到近的距离排序。

1
2
3
4
5
6
locations.sort(  
    function(b, a) {  
        return distance(home,a)-distance(home,b);  
    }  
);  
// locations sorted: pub, shops, library

或者根据字母顺序来对地点排序。

1
2
3
4
5
6
7
8
locations.sort(  
    function(a, b) {  
        if (a.name < b.name) return -1;  
        if (a.name > b.name) return 1;  
        return 0;  
    }  
);  
// locations sorted: library, pub, shops

基于javascript的数组排序,我们可以很容易的开发出可以重复使用、可用于任何对象、对象属性的排序方法。从这点上来说,javascript的排序比其他语言的更加灵活。

 

117 Responses to “ javascript数组排序的问题 ”

  1. mia pron khalifa说道:

    moFUzL wow, awesome blog article.Really looking forward to read more. Will read on

  2. You are my function models. Many thanks for your post

  3. Tattoo Shop说道:

    You should participate in a contest for the most effective blogs on the web. I will suggest this website!

  4. Lung Health说道:

    wow, awesome article post.Much thanks again. Much obliged.

  5. What as up mates, how is all, and what you wish for to say concerning this article, in my view its genuinely amazing designed for me.

  6. Very informative blog article.Much thanks again. Much obliged.

  7. montaj krovli说道:

    Some really prime blog posts on this internet site , saved to my bookmarks.

  8. The Silent Shard This may likely be fairly practical for many within your job opportunities I want to never only with my blogging site but

  9. This very blog is no doubt interesting additionally amusing. I have picked a bunch of useful tips out of this amazing blog. I ad love to visit it over and over again. Thanks a bunch!

  10. Oluwadamilare说道:

    This is a topic that as near to my heart Thank you! Where are your contact details though?

  11. see here说道:

    Wow, superb blog layout! How long have you been blogging for? you made blogging look easy. The overall look of your website is wonderful, as well as the content!

  12. Well I truly enjoyed reading it. This tip offered by you is very practical for accurate planning.

  13. Your style is really unique in comparison to other folks I have read stuff from. Thank you for posting when you ave got the opportunity, Guess I all just book mark this page.

  14. pre booked说道:

    Thanks again for the article post.Really thank you! Fantastic.

  15. I went over this web site and I believe you have a lot of excellent information, saved to my bookmarks (:.

  16. Well I really enjoyed reading it. This information offered by you is very practical for proper planning.

  17. I similar to Your Post about Khmer Funny

  18. explore说道:

    Sweet blog! I found it while searching on Yahoo News. Do you have any suggestions on how to get listed in Yahoo News? I ave been trying for a while but I never seem to get there! Thank you

  19. The Lost Ways说道:

    to be precisely what I am looking for. Would

  20. I really liked your post.Really thank you! Awesome.

  21. Share说道:

    Your style is very unique in comparison to other folks I have read stuff from. I appreciate you for posting when you ave got the opportunity, Guess I all just bookmark this site.

  22. our website说道:

    Outstanding post, I conceive people should learn a lot from this weblog its real user genial. So much wonderful information on here :D.

  23. Nwokolo说道:

    your weblog? My website is in the very same area of interest as yours and my visitors would really benefit from a lot of the information

  24. Sweet blog! I found it while surfing around on Yahoo News. Do you have any tips on how to get listed in Yahoo News? I ave been trying for a while but I never seem to get there! Cheers

  25. Sac Louis Vuitton Pas Cher Sac Louis Vuitton Pas Cher

  26. hampton bay说道:

    This is one awesome post.Really looking forward to read more. Really Great.

  27. MP3 Downloads说道:

    Wow, fantastic blog layout! How long have you been blogging for? you make blogging look easy. The overall look of your site is magnificent, let alone the content!

  28. Very interesting information!Perfect just what I was looking for!

  29. Manningham, who went over the michael kors handbags.

  30. Very good info. Lucky me I came across your blog by chance (stumbleupon). I ave bookmarked it for later!

  31. That is a great tip particularly to those fresh to the blogosphere. Simple but very precise info Appreciate your sharing this one. A must read article!

  32. Thanks-a-mundo for the post.Really looking forward to read more. Fantastic.

  33. Perfect work you have done, this internet site is really cool with good info.

  34. Vs model说道:

    You, my pal, ROCK! I found exactly the info I already searched everywhere and simply could not locate it. What an ideal web site.

  35. click here说道:

    Really informative blog article.Really looking forward to read more. Really Great.

  36. Lovely just what I was searching for. Thanks to the author for taking his time on this one.

  37. Website We Recommend You made some fine points there. I did a search on the matter and found most people will consent with your blog.

  38. girls说道:

    Thank you for your article post.Really looking forward to read more. Really Cool.

  39. It as hard to find educated people for this topic, however, you sound like you know what you are talking about! Thanks

  40. What as up, just wanted to say, I enjoyed this article. It was practical. Keep on posting!

  41. Wow, amazing blog layout! How long have you been blogging for? you made blogging look easy. The overall look of your website is wonderful, let alone the content!. Thanks For Your article about sex.

  42. Sisimiut说道:

    I really liked your article. Really Cool.

  43. try this说道:

    Lastly, an issue that I am passionate about. I ave looked for data of this caliber for your last numerous hours. Your internet site is drastically appreciated.

  44. Wow, great blog.Much thanks again. Really Cool.

  45. Incredible points. Sound arguments. Keep up the great spirit.

  46. Waec expo说道:

    Very good article. I absolutely appreciate this website. Keep writing!

  47. Waec expo说道:

    There is apparently a lot to identify about this. I assume you made various good points in features also.

  48. Im grateful for the post.Really thank you! Cool.

  49. stop bullying说道:

    I truly appreciate this article.Much thanks again. Cool.

  50. This unique blog is really awesome as well as factual. I have discovered a lot of useful tips out of this amazing blog. I ad love to come back over and over again. Cheers!

  51. website and I ad like to find something more safe.

  52. Open heaven说道:

    Muchos Gracias for your blog.Much thanks again. Fantastic.

  53. Remarkable Post Major thanks for this remarkable article. Thanks Again. Will read on

  54. Incredible mastewq! This blog looks just like my old one! It as on a entirely different subject but it has pretty much the same page layout and design. Outstanding choice of colors!

  55. Very nice info and straight to the point. I am not sure if this is truly the best place to ask but do you folks have any ideea where to hire some professional writers? Thanks

  56. Why people still make use of to read news papers when in this technological world all is existing on net?

  57. It as not that I want to copy your web site, but I really like the design and style. Could you let me know which design are you using? Or was it tailor made?

  58. Wohh precisely what I was searching for, thanks for putting up.

  59. entclass说道:

    Pretty! This has been an incredibly wonderful post. Many thanks for providing this info.

  60. Wow, awesome blog layout! How long have you been blogging for? you make blogging look easy. The overall look of your web site is wonderful, let alone the content!

  61. This blog was how do you say it? Relevant!! Finally I have found something which helped me. Thanks!

  62. Laughter and tears are both responses to frustration and exhaustion. I myself prefer to laugh, since there is less cleaning up to do afterward.

  63. News info I was reading the news and I saw this really interesting info

  64. That is a great tip especially to those new to the blogosphere. Brief but very precise information Many thanks for sharing this one. A must read article!

  65. visit website说道:

    Very good post! We are linking to this great post on our site. Keep up the good writing.

  66. official site说道:

    It as hard to find well-informed people on this subject, however, you sound like you know what you are talking about! Thanks

  67. Very neat article.Much thanks again. Awesome.

  68. The Silent Shard This could in all probability be quite practical for many within your work I plan to will not only with my website but

  69. Some genuinely nice stuff on this web site , I it.

  70. for more info说道:

    Really enjoyed this blog article.Much thanks again. Fantastic.

  71. This awesome blog is definitely interesting additionally diverting. I have found a bunch of interesting things out of it. I ad love to return over and over again. Cheers!

  72. wow, awesome article post.Much thanks again. Really Great.

  73. Wow! This can be one particular of the most helpful blogs We have ever arrive across on this subject. Basically Wonderful. I am also an expert in this topic so I can understand your effort.

  74. Thanks for sharing, this is a fantastic blog.Really looking forward to read more. Will read on

  75. social说道:

    Wow, awesome blog layout! How long have you been blogging for? you made blogging look easy. The overall look of your website is wonderful, let alone the content!

  76. facebook说道:

    this topic for a long time and yours is the greatest I have

  77. you can check说道:

    Saved as a favorite, I like your website!

  78. I think this is a real great post.Really thank you!

  79. ads说道:

    Really enjoyed this blog.Thanks Again. Will read on

  80. Your style is really unique compared to other people I have read stuff from. I appreciate you for posting when you have the opportunity, Guess I all just bookmark this web site.

  81. check here说道:

    It as not that I want to duplicate your website, but I really like the layout. Could you let me know which theme are you using? Or was it especially designed?

  82. more info说道:

    you have done a excellent task on this topic!

  83. I\ ave been using iXpenseIt for the past two years. Great app with very regular updates.

  84. MIAMI SEO说道:

    Thanks so much for the article.Really looking forward to read more. Keep writing.

  85. genuine parts说道:

    Major thanks for the blog.Really looking forward to read more.

  86. latest song说道:

    There is visibly a bundle to realize about this. I assume you made various nice points in features also.

  87. Thanks for sharing, this is a fantastic blog post.Thanks Again. Keep writing.

  88. This blog is obviously entertaining and besides informative. I have chosen a bunch of interesting stuff out of it. I ad love to visit it again and again. Thanks!

  89. Wow! This could be one particular of the most useful blogs We ave ever arrive across on this subject. Basically Fantastic. I am also an expert in this topic so I can understand your hard work.

  90. Wow, this post is pleasant, my younger sister is analyzing these kinds of things, thus I am going to tell her.

  91. I will make sure to bookmark it and return to read more of your useful information.

  92. Game Online说道:

    Im thankful for the blog post.Really looking forward to read more. Keep writing.

  93. There is definately a great deal to know about this topic. I like all of the points you made.

  94. Lisbon tours说道:

    your blog posts. Any way I will be subscribing to your feeds and even I achievement you

  95. topic, made me personally consider it from numerous various

  96. promo说道:

    The new Zune browser is surprisingly good, but not as good as the iPod’s. It works well, but isn’t as fast as Safari, and has a clunkier interface. If you occasionally plan on using the web browser that’s not an issue, but if you’re planning to browse the web alot from your PMP then the iPod’s larger screen and better browser may be important.

  97. get说道:

    If you’re still on the fence: grab your favorite earphones, head down to a Best Buy and ask to plug them into a Zune then an iPod and see which one sounds better to you, and which interface makes you smile more. Then you’ll know which is right for you.

  98. kouponkabla说道:

    Hands down, Apple’s app store wins by a mile. It’s a huge selection of all sorts of apps vs a rather sad selection of a handful for Zune. Microsoft has plans, especially in the realm of games, but I’m not sure I’d want to bet on the future if this aspect is important to you. The iPod is a much better choice in that case.

  99. Some really interesting information, well written and generally user genial.

  100. clothing store说道:

    Is that this a paid subject or did you customize it your self?

  101. Zebra说道:

    Really appreciate you sharing this blog article. Cool.

  102. This website definitely has all of the information I needed concerning this subject and didn at know who to ask.

  103. Salute! Thank you very much for this marvelous website. It was fantastic joy to read.

  104. Poker Galaxy说道:

    May I simply just say what a relief to find someone that truly understands what they

  105. I was seeking this particular info for a long time. Thank you and good

  106. pals ans additionally sharing in delicious. And of

  107. dinnercoupons说道:

    Wow! This can be one particular of the most beneficial blogs We have ever arrive across on this subject. Basically Great. I am also a specialist in this topic so I can understand your hard work.

  108. This is a topic that’s close to my heart…
    Thank you! Exactly where are your contact details though?

  109. mia pron khalifa说道:

    OTGLeN Try to remember the fact that you want to own an virtually all comprehensive older getaway.

  110. What kind of things can not circulate through the network.

  111. I visit every day a few web sites and websites to read articles, however this webpage presents quality based articles.

  112. Well I definitely enjoyed studying it. This post procured by you is very constructive for correct planning.

  113. Very good info. Lucky me I came across your blog by accident (stumbleupon). I ave bookmarked it for later!

  114. Simply wanna input that you have a very decent website , I like the style and design it actually stands out.

  115. Thank you ever so for you blog.Really thank you! Great.

  116. Thank you ever so for you blog article.Really thank you! Really Great.

  117. Seriously.. thank you for starting this up. This web site is one thing that as needed on the web, someone with some originality! Here is my weblog useful reference

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>