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,; // [1, 2, 3] "[object Arguments]" 
  var argsArr = slice(args, 0);
  console.log(argsArr,; // [1, 2, 3] "[object Array]" 

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:"div"));

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

console.log('string')); // ["s", "t", "r", "i", "n", "g"] 
console.log( 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:


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

console.log({name: 'obj'})); // []
console.log({0: 'zero', 1: 'one'})); // []
console.log({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: