Apply Method
Apply is a method available to all functions. Its signature is as follows:
Func. apply (thisValue, [arg1, arg2,...])
If thisValue is not taken into account, the above call is equivalent:
Func (arg1, arg2 ,...)
That is to say, apply allows us to "Unbind" an array into parameters and pass them to the calling function. Let's take a look at the three tips used by apply.
Tip 1: pass an array to a function that does not accept an array as a parameter
JavaScript does not return the maximum value of an array. however, there is a function Math. max returns the maximum value of any number of value types. with apply, we can achieve our goal:
Copy codeThe Code is as follows:> Math. max. apply (null, [10,-1, 5])
10
Note: if one of the parameters of the Math. max method is converted to NaN, the method returns NaN directly.Copy codeThe Code is as follows:> Math. max (1, null) // equivalent to Math. max (1, 0)
1
> Math. max (1, undefinded) // equivalent to Math. max (1, NaN)
NaN
> Math. max (0,-0) // The ratio of positive to zero is greater than that of negative and different from that of =
0
> Math. max (-0,-1) // The negative zero ratio is greater than-1.
-0
Tip 2: Fill in a sparse array
Gaps in the array
In JavaScript, an array is a ing between numbers and values. therefore, if an element (a gap) is missing from an index and the value of an element is undefined, there are two different situations. the former is in Array. related methods in prototype (forEach, map, etc .) the traversal will skip the missing elements, and the latter will not:Copy codeThe Code is as follows:> ["a", "B"]. forEach (function (x) {console. log (x )})
A
> ["A", undefined, "B"]. forEach (function (x) {console. log (x )})
A
Undefined
Note: here the author says, "array is a ing between numbers and values", which is strictly incorrect. The correct statement is that "array is a ing between strings and values ". the following is evidence:Copy codeThe Code is as follows:> for (I in ["a", "B"]) {
Console. log (typeof I) // the index of the array is actually a string
}
"String"
"String"
> ["A", "B"]. forEach (function (x, I ){
Console. log (typeof I) // The I here is actually not an index, but a number-type accumulators.
})
"Number"
"Number"
You can use the in operator to detect gaps in the array.Copy codeThe Code is as follows:> 1 in ["a", "B"]
False
> 1 in ["a", undefined, "B"]
True
Note: here we can use 1 because the in operator converts 1 to "1 ".
When you try to read the value of this gap, undefined will be returned, which is the same as the actual undefined element.Copy codeThe Code is as follows:> ["a", "B"] [1]
Undefined
> ["A", undefined, "B"] [1]
Undefined
Note: [1] will also be converted to ["1"]
Fill gaps
Apply is used with Array (new is not required here). You can fill gaps in the Array into undefined elements:Copy codeThe Code is as follows:> Array. apply (null, ["a", "B"])
['A', undefined, 'B']
This is because apply does not ignore the gaps in the array and passes the gaps as the undefined parameter to the function:Copy codeThe Code is as follows:> function returnArgs () {return []. slice. call (arguments )}
> ReturnArgs. apply (null, ["a", "B"])
['A', undefined, 'B']
However, if the parameter received by the Array method is a separate number, this parameter is treated as the Array length and a new Array is returned:Copy codeThe Code is as follows:> Array. apply (null, [3])
[,]
Therefore, the most reliable method is to write such a function to do this job:Copy codeThe Code is as follows: function fillHoles (arr ){
Var result = [];
For (var I = 0; I <arr. length; I ++ ){
Result [I] = arr [I];
}
Return result;
}
Run:Copy codeThe Code is as follows:> fillHoles (["a", "B"])
['A', undefined, 'B']
In Underscore_. CompactThe function removes all dummy values from the array, including gaps:
Copy codeThe Code is as follows:> _. compact (["a", "B"])
['A', 'B']
> _. Compact (["a", undefined, "B"])
['A', 'B']
> _. Compact (["a", false, "B"])
['A', 'B']
Tip 3: Flat Arrays
Task: convert an array containing multiple array elements into a first-order array. We use the apply unwrapped array capability to work with concat to do this:Copy codeThe Code is as follows:> Array. prototype. concat. apply ([], ["a"], ["B"])
['A', 'B']
You can also mix non-array elements:Copy codeThe Code is as follows:> Array. prototype. concat. apply ([], ["a"], "B"])
['A', 'B']
The thisValue of the apply method must be specified as [], because concat is an array method rather than an independent function. The limit of this writing method is that it can only flat second-order arrays at most:Copy codeThe Code is as follows:> Array. prototype. concat. apply ([], [["a"], ["B"])
[['A'], 'B']
Therefore, you should consider an alternative. For example, the _. flatten function in Underscore can process nested arrays of any number of layers:
Copy codeThe Code is as follows:> _. flatten ([[["a"], ["B"])
['A', 'B']
Reference
JavaScript: sparse arrays vs. dense arrays
ECMAScript. next: Array. from () and Array. ()