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

How to use sort method

不言
不言Original
2019-02-15 17:48:0013902browse

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()

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>

The running results are as follows:

1,2,4,5,8

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!

Statement:
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