Home  >  Article  >  Web Front-end  >  Usage examples of javascript Array.prototype.slice_javascript skills

Usage examples of javascript Array.prototype.slice_javascript skills

WBOY
WBOYOriginal
2016-05-16 17:15:20828browse

Often, you can see Array.prototype.slice(arguments, 0); This writing method can be used within function() {}, which can convert the function parameter list into a real array. Please see an example:

Copy code 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 function parameter list arguments changes to Array in one second after being called through slice.
Similarly, you can also convert the selected DOM elements into an array:
Copy the code The code is as follows:

slice.call(document.querySelectorAll("div"));

Following the clues, let’s think about it, can the slide method convert the object into an array? Please see the example:
Copy the code 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 will be converted directly to an array.
However, numbers and Boolean values ​​will be converted into an empty array:
Copy code The code is as follows:

console.log(slice.call(33));
console.log(slice.call(true));

Ordinary objects will also be converted into Empty array, unless you add a length attribute to it:
Copy code 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 also be used to clone an array:
Copy code The code is as follows :

var srcArr = [1,2,3];
var newArr = srcArr.slice(0);
console.log(srcArr, newArr); // [1 ,2,3] [1,2,3]
console.log(srcArr == newArr); // false
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn