apply() usage

The apply() method calls a function with a given this value and the parameters provided in the form of an array (or array-like object).

Note: The function of the call() method is similar to that of the apply() method. The difference is that the call() method accepts a parameter list, while the apply() method accepts an array of parameters.
Syntax: func.apply(thisArg, [argsArray])

Use apply to add items of an array to another array
We can use push to append elements to an array. Since push accepts a variable number of parameters, it is also possible to append multiple elements at once.

However, if the parameter of push is an array, it will add the array as a single element instead of adding each element in the array, so we will end up with an array in the array. What if you don't want this? Concat meets our needs, but instead of adding elements to an existing array, it creates and returns a new array. However, we need to append the elements to the existing array... so how do we do it? Do you want to write a loop? Of course not!

apply is really useful!


var array = ['a', 'b'];
var elements = [0, 1, 2];
//concat()
//array.concat(elements); //['a','b'] 不改变原有数组
var newArr = [];
newArr = array.concat(elements);
console.info(newArr ); // 返回新数组["a", "b", 0, 1, 2] 
// apply()
array.push.apply(array, elements);
console.info(array); // ["a", "b", 0, 1, 2]

Use apply and built-in functions

/* 找出数组中最大/小的数字 */
var numbers = [5, 6, 2, 3, 7];

/* 使用Math.min/Math.max以及apply 函数时的代码 */
var max = Math.max.apply(null, numbers); /* 基本等同于 Math.max(numbers[0], ...) 或 Math.max(5, 6, ..) */
var min = Math.min.apply(null, numbers);

/* 对比:简单循环算法 */
max = -Infinity, min = +Infinity;

for (var i = 0; i < numbers.length; i++) {
    
    
  if (numbers[i] > max)
    max = numbers[i];
  if (numbers[i] < min)
    min = numbers[i];
}

Note: If you call apply as above, there is a risk of exceeding the upper limit of the JavaScript engine parameter length. The consequences of passing too many parameters (such as 10,000) to a method are different in different JavaScript
engines. (There is an
upper limit for the number of hard-coded parameters in the JavaScriptCore engine : 65536). This is because this restriction (actually a natural manifestation of any behavior that uses a large stack space) is ambiguous. Some engines will throw exceptions, and worse, other engines will directly limit the number of parameters passed into the method, causing parameters to be lost. For example, suppose the upper limit of the method parameter of a certain engine is 4 (in fact, the limit is much higher). In
this case, after the above code is executed, the parameters that are actually passed to apply are 5, 6, 2, 3, and Not a complete array.

If your parameter array may be very large, then it is recommended to use the following hybrid strategy: Divide the array and pass it to the target method circularly:

function minOfArray(arr) {
    
    
  var min = Infinity;
  var QUANTUM = 32768;
  for (var i = 0, len = arr.length; i < len; i += QUANTUM) {
    
    
    var submin = Math.min.apply(null, arr.slice(i, Math.min(i + QUANTUM, len)));
    min = Math.min(submin, min);
  }
  return min;
}
var min = minOfArray([5, 6, 2, 3, 7]); //2

Use apply to link the constructor

function MyConstructor (arguments) {
    
    
    for (var nProp = 0; nProp < arguments.length; nProp++) {
    
    
        this["property" + nProp] = arguments[nProp];
    }
}

var myArray = [4, "Hello world!", false];
var myInstance = new MyConstructor(myArray); //Fix MyConstructor.construct is not a function
console.log(myInstance.property0);                // logs "4"
console.log(myInstance.property1);                // logs "Hello world!"
console.log(myInstance.property2);                // logs "false"
console.log(myInstance instanceof MyConstructor); // logs "true"
console.log(myInstance.constructor);              // logs "MyConstructor"

reference

Guess you like

Origin blog.csdn.net/weixin_42549581/article/details/114021198