SoFunction
Updated on 2025-04-10

Prototype Learning Tool Function Learning ($A Method)

$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 , but is the preferred way of casting to an Array.
Copy the codeThe code is as follows:

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

If the passed parameter is null, undefined and false will directly return to the empty array
If the toArray method is included in the parameter object passed in, this directly calls the toArray method of the parameter. Because many Prototype objects have already defined the toArray method, you can directly call the toArray method.
For example:
Copy the codeThe 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, and 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 of the prototype help document, which may better illustrate the function:
Copy the codeThe code is as follows:

/*The well-known DOM method () 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 , so instead we cast the returned NodeList to an Array:*/
var paras = $A(('p'));
();
$(()).show();

Another point:
= $A;
The from static method of array object and $A is a method