It's a good start, congratulations.-----about sort ()

Source: Internet
Author: User

Feel that I have lived for the rest of my life never wrote a blog, this is the first time, and is not a note is to learn, first congratulate himself, there is a very good beginning, no matter can not give up, anyway is to learn to do something.

This time there is a home, 1:30 will also do not know what to write, anyway, but also record some things, casually write it.

var arr = [{name: "A", Age:16},{name: "B", Age:106},{name: "C", Age:20},{name: "D", age:23}];

Sort by age name, which ultimately requires output a,c,d,b;

Final completion

<script>var arr = [{name: "A", Age:16},{name: "B", Age:106},{name: "C", Age:20},{name: "D", age:23}]; Arr.sort (function(A, b) {return a.age>b.age;});  for (var i=0;i<arr.length;i++) {    console.log (arr[i].name)}</script>

Actually knew sort () has the sorting function, but did not expect to be able to use this

Analysis:

If you sort an array, it's usually written like this.

var arr=[1,3,2,4,5];arr.sort (); Console.log (arr);

I'll make it better.

var arr=[1,3,2,4,5];arr.sort (function(b) {return A-B}); Console.log (arr) ;

After listening to lectures to know, at the beginning of the time is so written, in fact, in order to take two numbers to compare the size

var arr=[1,103,2,4,5];arr.sort (functionif(a<b) {            return -1elseif(a>b) {     return 1  Else {     return 0;}}); Console.log (arr);

Only, return-1, can also be written -5,-0.5 ... any negative number can be

After changing to a-B, a negative number can be an integer or 0

  

The beginning, congratulations, is a good start-----about sort ()

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.