Home > Web Front-end > JS Tutorial > How to use sort method

How to use sort method

不言
Release: 2021-04-20 14:40:33
Original
13901 people have browsed it

The sort method is used to sort the array. Its usage syntax is "array.sort()"; the sort function can have the parameter "[compareFunction]". This parameter is a comparison function and is used according to the Different attributes and different orders sort elements.

How to use sort method

The operating environment of this article: windows7 system, javascript version 1.8.5, Dell G3 computer.

The sort method is a built-in method in JavaScript, which is used to sort arrays. Arrays can be of any type, namely strings, numbers, characters, etc. Let’s take a look at the specific use of the sort method in this article.

Let’s first take a look at the basic syntax of sort()

array.sort()
Copy after login

In the sort function, you can have parameters [compareFunction], this parameter is Comparison function, used to sort elements according to different attributes and different orders. If there is no this parameter, the sorting will be in ascending order.

Let’s look at the specific examples

The code is as follows

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title></title>
</head>
<body>
<script> 
function func() { 
    var arr = [2, 5, 8, 1, 4] 
    document.write(arr.sort());  
} 
func(); 
</script> 
</body>
</html>
Copy after login

The running results are as follows:

1,2,4,5,8
Copy after login

The above is the entire content of this article, and more For more related content, you can pay attention to other related column tutorials on the PHP Chinese website! ! !

The above is the detailed content of How to use sort method. For more information, please follow other related articles on the PHP Chinese website!

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