Home > Web Front-end > JS Tutorial > body text

jQuery source code analysis makeArray method

黄舟
Release: 2017-07-19 09:49:20
Original
1443 people have browsed it

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);
Copy after login

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);
	}	
Copy after login

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;
	};
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!