Home >Web Front-end >JS Tutorial >JavaScript's native method to obtain the maximum (minimum) value in an array_Basic knowledge

JavaScript's native method to obtain the maximum (minimum) value in an array_Basic knowledge

WBOY
WBOYOriginal
2016-05-16 17:46:131201browse

The simplest way to get the maximum (minimum) value in an array is to traverse the array and find its maximum (minimum) value through comparison. But in fact, some shortcut methods have been provided in the native methods of javascript to achieve this function.
1 Array.prototype.sort

Copy code The code is as follows:

var a = [7,3,4,6,10];
a.sort(function(a,b){
return (a-b);})

Note that the comparison function in sort must be passed in. If this function is not passed, the result of a.sort() is [10,3,4,6,7];

2 Math.max,Math.min
Copy code The code is as follows:

var a = [7,3,4,6,10];
var max = Math.max.apply(Math,a);
var min = Math.min.apply(Math,a);
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