Array.prototype.slice.call() - Detailed explanation

1. Arguments

It is an array-like object. We often need to pass parameters into the function. JS stores all the parameters passed into this function in atguments. We can know atguments through the following code

let fn = function () {
    //arguments的用法
    console.log("arguments=>", arguments)
    //aguments的类型
    console.log("arguments类型=>", Object.prototype.toString.call(arguments))
    //...
}
fn(1, 2, 3, 4)

According to the type of arguments above is an object , js takes the attribute name of the first parameter we pass to the function as "0", the second parameter as "1", and so on, the attribute value is a number. We also observe that arguments is an array-like property length .

Two, Array, prototype

When we write a project, we often need to convert arguments into an array. Here I will expand one of the conversion methods in detail: Array.prototype.slice.call()

console.log("Array.prototype=>", Array.prototype)

As can be seen from the above, slice is a method on the prototype attribute of the built-in method Array() of js (note: the prototype attribute is an object).

 3. slice()

Returns selected elements from an existing array

  • When there are two parameters: array.slice(start, end)  intercepts the start data from the original array to the end
  • When there is no parameter: array.slice()  intercepts all the data of the original array slice does not need this to be of array type, only needs to have the length property

Slice was originally just a method of Array and String, why can it be used directly on the class array? We can look at the source code of slice()

function slice(start, end) { 
    var len = ToUint32(this.length), result = []; 
    for(var i = start; i < end; i++) { 
        result.push(this[i]); } return result; 
    }
}

It can be seen that the slice does not need this to be an array type, but only needs to have a length attribute. And the length attribute may not be a number type. When it cannot be converted to a value, ToUnit32(this.length) returns 0. Because the arguments object has a length attribute, of course you can use slice() to intercept the data in the arguments object

Four, call ()

We know that call() is a function that changes the pointing of this

let agrs = Array.prototype.slice.call(arguments)

At this point we point the object this from Array.prototype to arguments. In this way, arguments can use the method slice() of the array.

For details, please see: link

Guess you like

Origin blog.csdn.net/qq_52421092/article/details/129774398