How to understand how to understand Array.apply(null, {length:5}) in JavaScript

Actually this has nothing to do with Array, just happened to use Array.

I think this problem should start with Function.call and Function.apply.
The method functions of these two functions are the same, both to change the point of this.
The only difference is that the parameters are different. The second parameter of apply must be passed in an array.

First, you need a function to define an iAmArray;

 

var iAmArray = function(){
    return arguments;
};

Don't care about this here, here are three ways to call it normally:

 

//Convenient for you to copy to Console for testing, write it again here
var iAmArray = function(){
    return arguments;
};

// normal writing
iAmArray(1,2,3);
/*
    [1, 2, 3]
*/

//call writing
iAmArray.call(null,1,2,3);
/*
    [1, 2, 3]
*/

//apply writing
iAmArray.apply(null,[1,2,3]);
/*
    [1, 2, 3]
*/

When the apply method is called, it is estimated to be a small bug. As long as it is an Object and has a length, it is treated as an array. Actually, it has nothing to do with Array, and any function will do this.

 

//Convenient for you to copy to Console for testing, write it again here
var iAmArray = function(){
    return arguments;
};

var iHaveLength = function(length){
    this.length = length || 5;
    this[2] = "third element";
};

/*
   As long as it is an Object and has a length, it is treated as an array.
*/
iAmArray.apply(null, new iHaveLength());
/*
    [undefined, undefined, "third element", undefined, undefined]
*/
iAmArray.apply(null, new iHaveLength(3));
/*
    [undefined, undefined, "third element"]
*/

final summary

Then in fact, the second parameter only needs to be an array-like object. For example, {length: 5} can be regarded as an array-like object with a length of 5. Each element, such as v[0], is undefined.

所以,Array.apply(null, { length: 5}) 相当于
Array(undefined, undefined, undefined, undefined, undefined)


Thank you for reading the Shanghai front-end training article. For more reading or help, please click to get it.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325064539&siteId=291194637