Home >Web Front-end >JS Tutorial >Use and differences between apply and Math.max() functions
This time I will bring you the use and difference between apply and Math.max() functions. What are the precautions about the use and difference between apply and Math.max() functions. The following is a practical case. One Get up and take a look.
The following will introduce to you the problems of apply and Math.max() functions in js. The specific content is as follows:
var arr=[1,3,6,3,7,9,2]; console.log(Math.max.apply(null,arr));
I still don’t understand why an array can be calculated in this way# The maximum value of ##? I still can't figure it out, please give me some advice from a js expert.
Answer 1
Function.apply() is an OOP feature of JS, generally used to simulateinheritance and Extending the purpose of this, the above code can be understood like this:
XXX.apply is a method of calling a function, and its parameters are: apply(Function, Args), Function is the method to be called, Args is the parameter list, when Function is null, the default is as above,that is,
Math.max.apply(null, arr)can be considered as
apply(Math.max, arr)Then, arr is a parameter list , for the max method, its parameters are several numbers, that is,
Math.max(a, b, c, d, ...)When using apply, add all parameters to an array, that is,
arr = [a, b, c, d, ...]is substituted into the original formula,
Math.max.apply(null, [a, b, c, d, ...])is actually equivalent to
Math.max(a, b, c, d, ...)Here, the advantage of using apply is to improve performance in some JS engines.
Answer 2
Math.max() method supports passing multiple parameters, such as:
Math.max(1,4,2,3,7,5,6)
Math.max(new Array( 1,4,2,3,7,5,6)).
Supplement: The difference between Math.max.apply and Math.max in
The Math.max method in Javascript can find the largest number among the given parameters.
> Math.max('1','2','3.1','3.2') < 3.2 > Math.min(1,0,-1) < -1But if it is an array, it cannot be called like this. The apply method is used at this time:
apply 方法 (Function) (JavaScript) 调用函数,并用指定对象替换函数的 this 值,同时用指定数组替换函数的参数。 apply([thisObj[,argArray]]) thisObj 可选。 要用作 this 对象的对象。 argArrayOptional. A set of arguments to be passed to the function.
Cleverly make arrays can also call Math.max and Math.min.
> Math.max.apply(null, ['1','2','3.1','3.2']) < 3.2 > Math.min.apply(null, [1,0,-1]) < -1
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!
Detailed explanation of the use of Vue watch
##Detailed explanation of the steps to introduce icon icons in the Vue project
The above is the detailed content of Use and differences between apply and Math.max() functions. For more information, please follow other related articles on the PHP Chinese website!