The difference between math.max () and math.max () in JS is described in this article. The difference between math.max () and math.max () in JS is described in this article. Have certain reference value, the friend that has need to this can refer to study. If there are shortcomings, welcome to criticize and correct.

Apply and math.max () functions apply and math.max () functions apply and math.max ()

Var arr =,3,6,3,7,9,2 [1]; console.log(Math.max.apply(null,arr));Copy the code

The answer to 1

Function. Apply () is an OOP feature of JS that is used to emulate the use of inheriting and extending this. Apply (Function, Args), Function is the method to call, Args is the argument list, if Function is null, default is above, that is

Math.max.apply(null, arr)
Copy the code

Can be considered

apply(Math.max, arr)
Copy the code

Then, arR is a list of arguments, which for the Max method is a number of arguments, i.e

Math.max(a, b, c, d, ...)
Copy the code

When apply is used, all parameters are added to an array, i.e

arr = [a, b, c, d, ...]
Copy the code

So if I plug it in,

Math.max.apply(null, [a, b, c, d, ...] )Copy the code

In effect equivalent to

Math.max(a, b, c, d, ...) // Welcome to join the front-end full stack development exchange circle to learn exchange: 864305860Copy the code

The advantage of using Apply here is to improve performance in some JS engines.

Answer 2

The math.max () method supports passing multiple arguments, such as math.max (1,4,2,3,7,5,6), but it does not support passing an Array directly, such as math.max (new Array(1,4,2,3,7,5,6)). Here, as long as we have a way to break up the array, one by one, and pass it to math.max (), we’re done passing the array. All functions have the apply method, whose “arguments” take an array and pass each value in the array separately to the call. add: the difference between Math.max and Math.max in Javascript

The math.max method in Javascript evaluates the largest number in a given argument.

> Math.max('1'.'2'.'3.1'.'3.2'Math.min(1,0,-1) < -1Copy the code

But if it’s an array, you can’t do that. Here the apply method is used:

The apply method (Function) (JavaScript) calls the Function, replacing the Function's this value with the specified object and the Function's arguments with the specified array. apply([thisObj[,argArray]]) thisObj &emsp; &emsp; Optional. The object to be used as this object. argArrayCopy the code

Optional. The set of arguments to be passed to a function. Cleverly make arrays also callable to math.max and math.min.

> Math.max.apply(null, ['1'.'2'.'3.1'.'3.2'] < 3.2 > math.min. apply(null, [1,0,-1]) < -1Copy the code

conclusion

Thank you for watching, if there are shortcomings, welcome to criticize.