Home  >  Article  >  Web Front-end  >  Prototype learning tool function learning ($A method)_prototype

Prototype learning tool function learning ($A method)_prototype

WBOY
WBOYOriginal
2016-05-16 18:50:05797browse

$A method:
Accepts an array-like collection (anything with numeric indices) and returns its equivalent as an actual Array object. This method is a convenience alias of Array.from, but is the preferred way of casting to an Array .

Copy code The code is as follows:

function $A(iterable) {
if (!iterable) return [];
if ('toArray' in Object(iterable)) return iterable.toArray();
var length = iterable.length || 0, results = new Array(length);
while (length--) results[length] = iterable[length];
return results;
}

If the parameters passed in are null, undefined and false then Directly return an empty array
If there is a toArray method in the parameter object passed in, the toArray method of the parameter will be called directly. Because many Prototype objects have already defined the toArray method, you can directly call the toArray method
For example:
Copy code The code is as follows:

var array={
toArray : function() {
return [1,2,3];
}
}
//1,2,3
alert($A(array));

Next, create a new array based on the length of the parameter, then copy the elements in the parameter to the new array one by one, and finally return the new array object
The following is an explanation and example from the prototype help document that may better explain this. Function:
Copy code The code is as follows:

/*The well-known DOM method document.getElementsByTagName() doesn't return an Array, but a NodeList object that implements the basic array "interface." Internet Explorer does not allow us to extend Enumerable onto NodeList.prototype, so instead we cast the returned NodeList to an Array: */
var paras = $A(document.getElementsByTagName('p'));
paras.each(Element.hide);
$(paras.last()).show();

One more thing:
Array.from = $A;
The from static method of the array object and $A are the same method
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