JavascriptArray. prototype. slice not only extracts a new Array from an Array, but also has some other usage. Below we will explain these usage frequently. We can see the Array. prototype. slice (arguments, 0); this method can be used in function () {}, so that the function parameter list can be converted into a real array. Take an example:
The Code is as follows:
Var slice = Array. prototype. slice;
Var toString = Object. prototype. toString;
(Function (){
Var args = arguments;
Console. log (args, toString. call (args); // [1, 2, 3] "[object Arguments]"
Var argsArr = slice (args, 0 );
Console. log (argsArr, toString. call (argsArr); // [1, 2, 3] "[object Array]"
} (1, 2, 3 ))
We can see that the arguments parameter list of the function is changed to Array in one second after being called by slice.
Similarly, you can convert the selected DOM element to an array:
The Code is as follows:
Slice. call (document. querySelectorAll ("p "));
Let's see if the slide method can convert objects into arrays? See the example below:
The Code is as follows:
Console. log (slice. call ('string'); // ["s", "t", "r", "I", "n", "g"]
Console. log (slice. call (new String ('string'); // ["s", "t", "r", "I", "n", "g"]
Each time, the string is directly converted into an array.
However, digits and boolean values are converted into an empty array:
The Code is as follows:
Console. log (slice. call (33 ));
Console. log (slice. call (true ));
A normal object is also converted to an empty array, unless you add a length attribute to it:
The Code is as follows:
Console. log (slice. call ({name: 'obj '}); // []
Console. log (slice. call ({0: 'zero ', 1: 'one'}); // []
Console. log (slice. call ({0: 'zero ', 1: 'one', name: 'obj', length: 2}); // ["zero", "one"]
Also, it can be used to clone Arrays:
The Code is as follows:
Var srcArr = [1, 2, 3];
Var newArr = srcArr. slice (0 );
Console. log (srcArr, newArr); // [1, 2, 3] [1, 3]
Console. log (srcArr = newArr); // false