Home > Article > Web Front-end > jQuery source code analysis makeArray method
In jQuery, makeArray is a private method, which is mainly used to convert "array-like objects" Convert to array.
So what is "array-like object"?
For example, there is an arguments object in each function , which is a list of actual parameters and has the #length attribute. The actual parameters can also be accessed through subscripts.
function foo(){ //1 console.log(arguments.length); //10 console.log(arguments[0]); } foo(10);
In addition, objects of type HTMLCollection, NodeList are also "Array-like object".
They have 2 points in common:
1. They have the length attribute.
2. Elements can be accessed through subscripts.
Compared with arrays, array-like objects lack many convenient APIs, so many frameworks provide conversion methods.
The easiest way is to use the slice method on Array.prototype:
function makeArray(array){ return Array.prototype.slice.call(array); }
But jQuery for compatibility The early IE provided its own implementation.
var makeArray = function(array){ //存储元素的新数组 var ret = []; if(array != null){ var i = array.length; /* 分别对应四种非类数组对象情况: 1.没有length属性 2.为字符串 3.是函数 4.是window对象 */ if(i == null || typeof array === "string" || jQuery.isFunction(array) || array.setInterval) ret[0] = array; else while(i) ret[--i] = array[i]; } return ret; };
Its impact is 3:
1. Even if no parameters are passed, an empty array will be returned.
2. If array-like object is passed, a new element array will be returned.
3. If a non-array object is passed in, this object will be used as the first element of the new array.
The above is the detailed content of jQuery source code analysis makeArray method. For more information, please follow other related articles on the PHP Chinese website!