Home > Web Front-end > JS Tutorial > Array sorting, shuffling and search implementation code in JavaScript_javascript skills

Array sorting, shuffling and search implementation code in JavaScript_javascript skills

WBOY
Release: 2016-05-16 17:59:06
Original
1036 people have browsed it
1. Sorting:
The default sort() sorts by character encoding:
Copy code The code is as follows:



Now let it follow Sorting by numerical size:
Copy code The code is as follows:



Just pass a comparison function to sort. If the comparison function The value of is less than 0, which means that a must appear before b, otherwise it will appear after b.

2. Out of order:
Just let the comparison function return -1 or 1 randomly:
Copy Code The code is as follows:



3. Search:

Using sort() to search is quite new, haha, let’s see how it works.
Now I want to find all the elements containing the letter 'a' in the array. If there is no sort(), it seems that I can only use traversal. The efficiency of traversal... That is scary! ! The specific method is as follows:
Copy the code The code is as follows:



This way, the array contains letters' All the elements of a' are placed in front of the array, and after some simple processing, the search results can be output.
The above are the three methods I summarized for using sort() to operate arrays in JavaScript. If you are interested, you will find that sort() has many wonderful uses...
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