# Math. max and Math. max. apply in Javascript

- 2021-08-06 20:57:05
- OfStack

Recently, when I was doing a small case, I encountered such a usage as Math. max. apply. I rarely encountered it before, so I recorded it.

1Math.max

Syntax:
`Math.max(n1,n2,n3,...,nX)`

Return value: The max () method returns the number with the larger value in the specified parameter

```
var a = Math.max(1,2,3,4);
console.log(a); //4
```

However, if the data is placed in an array, it cannot be called like this at this time. The apply method is then used

2Math.max.apply

The apply () method calls a function. Simply understood as a way to call a function, but it can change the this pointing of the function and replace the parameters of the function with the specified array.

Syntax:
`fun.apply(thisArg, [argsArray]) `

Adding 1 here, the passed value is in the form of array, but what type of parameters are in the array and what type is returned. For example, the input array is a string, and what you get here is a string, and what you get is a value. For example, if you pass' abc ', you will return' abc '. (Supplementary note)

Return value: The return value of the apply () method is the return value of the function, because it is the calling function

```
var arr = [1, 66, 3, 99, 4];
var max = Math.max.apply(Math, arr);
var min = Math.min.apply(Math, arr);
console.log(max); //99
console.log(min); //1
```

2.1 Math. max. apply Extension Case

Here I will give another application case-automatically generating numbers (self-increasing)

Explanation: data is an json array, and each object in it has an id value

```
let maxBookCode = ()=>{
let arr = [];
// Traversal json Array, putting the id Deposit to arr In this empty array,
data.forEach((item)=>{
arr.push(item.id);
});
// Finally return to the inside id The number with the largest value
return Math.max.apply(null,arr);
}
```

External calls to maxBookCode () + 1 automatically generate numbers and are self-incremental.

Summarize