[javascript] js gets the largest number in the array

1. Get the maximum value with the help of the parameters of apply()

let data = [11, 22, 33, 44, 55];
let max = Math.max.apply(null, data);
console.log(max);  // 55

Since the parameter in max() cannot be an array, Math.max() is called with the apply(function,args) method, function is the method to be called, and args is an array object. When function is null, it defaults to the above, that is Equivalent to apply(Math.max, arr)

2. Get the maximum value with the help of the parameters of call()

let arr = [11, 22, 33, 44, 55];
let max = Math.max.call(null, 11, 22, 33, 44, 55);
console.log(max);

call() is similar to apply(), the difference is that the way of passing in parameters is different, the apply() parameter is an object and an array type object, and the call() parameter is an object and parameter list

3. Reverse the array reverse() after sort() to get the maximum value

let arr = [11, 22, 33, 44, 55];
let max = arr.sort().reverse()[0];
console.log(max);

sort() defaults to ascending order, and reverse() drops the array

4. sort() sorting, use the callback return value to reverse the array and get the maximum value

let arr = [11, 22, 33, 44, 55];
let max = arr.sort(function(a,b){
    
    
    return b-a;
})[0];
console.log(max);

ba from big to small, ab from small to big

Guess you like

Origin blog.csdn.net/hzxOnlineOk/article/details/128000591