Although JS's application method is not seen in the usual use, but in some places use is very helpful, here and you say two more practical examples:
1. Maximum minimum value of the array
To find the maximum minimum value in the array, JS has the corresponding method: Math.min (), Math.max (), but the two methods have an inconvenient place is that its parameters can not be an array, but a single element value, that is (Para1,para2,para3 ...). So the use is not that convenient, but we can use this method:
var min = Math.min.apply (null, arr); var max = Math.max.apply (null, arr);
2. Array merging. The merging of arrays is also the same as the maximum value, we can use simple push (PARA1); But we can also use a simpler approach:
Array.prototype.push.apply (ArrA, ARRB); The array arrb is push into the array arra.
Here's why you can use it. From another article about apply, we can see that the second parameter of the Apply method of function is an array collection, when called, he needs not an array, but why he gave me an array I can still parse the array into one parameter, This is a clever use of apply, you can convert an array by default to a parameter list ([PARAM1,PARAM2,PARAM3] to PARAM1,PARAM2,PARAM3), so using the variable feature, we implemented the above function.
Here is my complete code, easy to learn to understand.
$ (' #getMinMax '). Click (function () { var arr = [1, 2, 3, 4, 5, 6, 7, 0.9, one]; var min = Math.min.apply (null, arr); var max = Math.max.apply (null, arr); Alert (' min: ' min ' max: ' Max ') ; $ (' #unite '). Click (function () { var arrA = [' 1 ', ' 2 ', ' 3 ']; var ARRB = [4, 5, 6]; Array.prototype.push.apply (ArrA, ARRB); var str = ' newarr:['; for (var i = 0; i < arra.length; I ) { str = arra[i] ', '; } str = STR.SUBSTR (0, str.length-1) '; alert (str); });
JS skillfully using the Apply method to achieve the value of the array and merge