Home  >  Article  >  Web Front-end  >  How to get the maximum value in an array

How to get the maximum value in an array

php中世界最好的语言
php中世界最好的语言Original
2018-03-09 16:24:382516browse

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!

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