Home >Web Front-end >JS Tutorial >How to get the maximum value in an array
This time I will show you how to get the maximum value in an array, what are the precautions for getting the maximum value in an array, the following is a practical case, let’s take a look .
1. The way you like;
let arr = [1,2,3,4,5,5,6,7];console.log(1,Math.max.apply(Math,arr));let arr2 = Math.max(1,2,3,4,5,5,6,7);console.log(2,arr2);let arr3 = Math.max.call(Math,1,2,3,4,5,5,6,7);console.log(3,arr3);
2. The more troublesome way
function getMax(arr) { for (let i = 0; i < arr.length; i++) { if(arr[i] >= arr[0]){ //如果后面的数组比第一个大互换位置 let k = arr[0]; arr[0] = arr[i]; arr[i] = k; } } return arr[0]; }console.log(4,getMax(arr))
I believe you have mastered the method after reading the case in this article. For more exciting things, please pay attention to php Chinese website Other related articles!
Related reading:
How to filter out false, null, 0, "", undefined, and NaN values in a js array
WOW.js that makes the page move
table tr th and table tr td have too many fonts, how to use CSS to solve it
The above is the detailed content of How to get the maximum value in an array. For more information, please follow other related articles on the PHP Chinese website!