An example of using javascript array.prototype.slice

  • 2020-03-29 23:43:23
  • OfStack

Often, you can see Array. Prototype.slice (arguments, 0); This method can be used within function() {} to convert the list of arguments to an actual array. Here's an example:

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 in the function's argument list change into an Array a second after the call to slice.
Similarly, you can convert selected DOM elements into arrays:

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

With that in mind, can slide transform objects into arrays? Here's an example:

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 converted directly into an array.
However, the number of Boolean values will be converted to an empty array:

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

Normal objects will also be converted to an empty array, unless you add a length property to it:

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:

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

Related articles: