What's the difference between Array.prototype.slice.call (arrary,args) and an array calling the slice method directly in js?

what"s the difference between operands such as Array.prototype.slice.call (arrary,args) and arrays calling slice methods directly in javascript

Mar.09,2021

The

array calls the slice method directly so that returns a shallow copy of a selected array from start to end (excluding the end) to a new array object.
you can use Array.prototype.slice.call (arguments) to convert Array-like objects / collections into a new array.
or abbreviated to [] .slice.call (arguments)
in addition, the new API Array.from in ES6 can also transform class array objects into real arrays
in practical applications, class array objects are often NodeList collections returned by DOM operations and arguments of functions
for example:

let arrayLike = {
  '0': 'a',
  '1': 'b',
  '2': 'c',
  length: 3
}
// es5 
var arr =  Array.prototype.slice.call(arrayLike) // ["a", "b", "c"]
var arr = [].slice.call(arrayLike) // ["a", "b", "c"]
// es6
let arr2 = Array.from(arrayLike) // ["a", "b", "c"]

reference link slice


args belongs to the class array object, which is similar to the content obtained by document.getElementsByClassName. It only has the array structure but does not have the prototype method of the array, so it will need to execute the slice method of binding data in the form of Array.prototype.slice.call.

Menu