There is a very common question, "what is the difference between call and apply?" "Everyone knows the answer: they differ only in the way they accept parameters, the second argument passed to call must be enumerated, and the second argument passed to apply is an array, as follows
function sum (num1,num2) { return num1 + num2;} function Callsum (num1,num2) { return sum.call (this, num1,num2);} function Applysum (num1,num2) { return sum.apply (this, [num1,num2]); // or return sum.apply (this,arguemnts);}
That is, the Apply function actually has a function: to convert the passed-in parameter array into the form of a parameter list, passing through. With this feature of apply, many operations can be simplified.
(1) Find the maximum/minimum value in the array
var arr = [1,2,3,4,5];console.log (Math.max.apply (null, arr)); // 5 Apply Method Console.log (Math.max (1,2,3,4,5)); // 5 Original Method
1) Both methods in the above code are implemented to find the maximum value, but if the array is long or only arr (not know the specific values), the original method will be cumbersome (to column a long number, or require the array to be converted to a list first), and the Apply method directly apply its own conversion function, It's easy to implement.
2) The first parameter in the Apply method is null, because there is no object to invoke apply, we just need to use this method to help calculate the line.
(2) merging of two arrays
var = [arr1]var arr2 = [4,5,6]; Array.prototype.push.apply (ARR1,ARR2); Console.log (arr1); // [1,2,3,4,5,6]
To implement the array merging is also troublesome, according to the above method to arr1 call apply, you can simply put arr2 in order to merge into the array arr1.
Summary: The above two usages all have one thing in common, that is, you need to convert the array into a list form, and apply just can do this function.