Home > Web Front-end > JS Tutorial > body text

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

WBOY
Release: 2016-05-16 17:46:13
Original
1175 people have browsed it

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