Home > Web Front-end > JS Tutorial > js simulates the sort method of Array_javascript skills

js simulates the sort method of Array_javascript skills

WBOY
Release: 2016-05-16 19:07:17
Original
1270 people have browsed it

JavaScript's Array object has a sort method, which is used to sort array elements. This method defaults to ascending order of array items in ASCII character order.
For example, [6,7,9,1,-1].sort(); after execution, the array becomes [-1,1,6,7,9].

For descending order or non-string sorting, this method cannot be performed well.

Of course, sort has an optional parameter, which can help us solve this problem. By passing in a function for sort, sort sorts based on the function return value.

The array is the two elements in the array that are passed into the function by default, such as a and b. If the function return value is greater than 0, the sorting method is b, a. If the return value is less than 0, the sorting method is The result is a,b.

The specific meaning is difficult to explain. At the beginning, I didn’t understand how this sort was sorted.

If you know its implementation process, you will understand its sorting principle. The implementation of

sort is actually very similar to a simple bubble sort.

I simulated it today. If you understand this function, you will definitely understand the principle of sort.


[Ctrl A select all Note: If you need to introduce external Js, you need to refresh to execute
]
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