Home  >  Article  >  Web Front-end  >  Array.apply analysis in JavaScript

Array.apply analysis in JavaScript

小云云
小云云Original
2018-02-28 13:39:564025browse

Let’s first look at a question:

How to understand the {length:5} of Array.apply(null, {length:5})? This article mainly shares with you Array in JavaScript .apply analysis, I hope it can help everyone.

I have tested it

Array.apply(null, {length:5}) //返回[undefined, undefined, undefined, undefined, undefined]
Array.apply(null, [{length:5}])和Array({length:5})返回的结果是一样的,为[[object Object] { length: 5 }]

I can still understand the second and third ones! How to understand the first one?

Actually, this has nothing to do with Array, I just happened to encounter it when using Array.

I think this problem should be started with Function.call and Function.apply.
The methods of these two functions have the same function, both of which are used to change the pointer of this.
The only difference is that the parameters are different. The second parameter of apply must be passed into the array.

First you need a function to define an iAmArray;

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

Don’t worry about this here, here are three ways to call it normally:

//方便你复制到 Console 中测试,在此再写一遍
var iAmArray = function(){
    return arguments;
};

//普通写法
iAmArray(1,2,3);
/*
    [1, 2, 3]
*/

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

//apply写法
iAmArray.apply(null,[1,2,3]);
/*
    [1, 2, 3]
*/
## When calling in the #apply method, it is probably a small bug. As long as it is an Object and has a length, it is treated as an array. It actually has nothing to do with Array. This will happen to any function.

//方便你复制到 Console 中测试,在此再写一遍
var iAmArray = function(){
    return arguments;
};

var iHaveLength = function(length){
    this.length = length || 5;
    this[2] = "第三个元素";
};

/*
   只要是 Object,还有length,他就当作数组处理了。
*/
iAmArray.apply(null, new iHaveLength());
/*
    [undefined, undefined, "第三个元素", undefined, undefined]
*/
iAmArray.apply(null, new iHaveLength(3));
/*
    [undefined, undefined, "第三个元素"]
*/

Final summary

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. , the length is 5, and each element, such as v[0] is undefined.

So, Array.apply(null, { length: 5}) is equivalent to

Array(undefined, undefined, undefined, undefined, undefined)


The above is the detailed content of Array.apply analysis in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn