[].shift.call( arguments) and [].slice.call( arguments) explained

 

Classic [].slice.call( arguments )on the Internet has a lot of explanation, most of "the class array object into an array of objects" . Indeed this is what we want to achieve! But this only shows that the result does not answer the principle.
Some basic knowledge:

[].slice.call( arguments )
// 等效于
Array.prototype.slice.call( arguments )

Personal understanding:
turn it argumentsinto an array object!
Spirit can write less and less to write, can not write the idea is not to write , think slice():可从已有的数组中返回选定的元素。
slicedoes not change the original array, but returns a sub-array.

let kindle = [1,2,3,4,5,6,7]
console.log(kindle.slice())  // [ 1, 2, 3, 4, 5, 6, 7 ]

Then the next question comes again, it's argumentsnot an array object, you can't call an array method.
argumentsI want to convert to an array object, how do I convert it? forLoop and so on. . .

But can a small write less write, can not write, do not write
it again when unlocking a callfunction, or applyfunction. Both of these functions can change the function thisscope point, the function is running. The difference is that the parameters are different. The first parameter is an object or'this'. Note that this is in quotation marks. The second parameter of apply receives an array. Call does not. Call can have as many n parameters as you want.

Click here for a detailed explanation of the call function

sliceThe principle of the method is to traverse the original array (or class array) according to the incoming parameters (values), assign it to the new array and return. If there is no parameter, copy the entire original array (or class array), assign it to the new array and return.

The point is here
because the sliceinternal implementation uses the thisdelegate call object. Then when [].slice.call()an incoming argumentsobject when, through calla function to change the original slicemethod of thispoint to point arguments, and the argumentscopy operation, and then returns a new array. So far arguments, the purpose of converting the class array to the array is completed !

In fact, this can be understood as the method of letting the class array call the array!

[].shift.call( arguments )

[].shift.call( arguments )This is an example.
shift()The method deletes the first item in the array and returns the deleted item.
According to the above understanding, this code means: "delete and get argumentsthe first item"

Guess you like

Origin blog.csdn.net/u013946061/article/details/108269650