Home > Web Front-end > JS Tutorial > body text

Analysis of usage examples of sort() in javascript_javascript skills

WBOY
Release: 2016-05-16 16:17:03
Original
973 people have browsed it

This article analyzes the usage of sort() in javascript with examples. Share it with everyone for your reference. The specific analysis is as follows:

Syntax of function:

arrayObject.sort(sortby)
Copy after login

you think this is not the right way but you love it

The split function is also used here, the purpose is to get an array of strings, which is more commonly used. Then the values ​​in the array are sorted through the array's sorting function sort() to obtain a new array, and then the sorted string is obtained by looping through the contents of the array.

In the example, by default, it will be sorted according to ascii code.
What if it were numbers? Give it a try~

Modify the value in p as follows:

20 38 19 32 654 2 123 454 4

The running result is: 123 19 2 20 32 38 4 454 654

It is sorted according to the character encoding, not the size of the value.

If you want to sort numbers, you need to write a few more lines of code:

The modified code is as follows:

originarr = originarr.sort(function(a,b){      
  return a - b;      
});
Copy after login

Run results: 2 4 19 20 32 38 123 454 654

The above sorting is in positive order. If it is in reverse order, then you need to change it again:
Just change return a - b; in the function to return b - a.

If it is alphabetical sorting, the changed code is as follows:

originarr = originarr.sort(function(a,b){ 
  if(a > b) return -1; 
  if(a < b) return 1; 
  return 0; 
});
Copy after login

I hope this article will be helpful to everyone’s JavaScript programming design.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template