- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
- "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <html>
- <head>
- <title>$A</title>
- <script language="javascript" src="prototype.js"
- type="text/javascript"></script>
- <script language="javascript" type="text/javascript">
- function showOptions() {
- //先获取id为listFramework的对象,再由对象找到tagName为option的内容
- var someNodeList = $("lstFramework").getElementsByTagName("option");
- var nodes = $A(someNodeList);
- var info = [];
- nodes.each (function(node){
- info.push(node.value + ": " + node.innerHTML);
- });
- alert(info.join("\r\n"));
- }
- </script>
- </head>
- <body>
- <form>
- <select id="lstFramework" size="10">
- <option value="1">Prototype</option>
- <option value="2">Script.aculo.us</option>
- <option value="3">Dojo</option>
- <option value="4">YUI</option>
- </select>
- <input onclick="showOptions();" type="button" value="Show the options">
- </form>
- </body>
- </html>
看看官方的解释你就都明白了:
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
.
The primary use of $A
is to obtain an actual Array
object based on anything that could pass as an array (e.g. the NodeList
or HTMLCollection
objects returned by numerous DOM methods, or the predefined arguments
reference within your functions).
The reason you would want an actual Array
is simple: Prototype extends Array to equip it with numerous extra methods, and also mixes in the Enumerable
module, which brings in another boatload of nifty methods. Therefore, in Prototype, actual Array
s trump any other collection type you might otherwise get.
The conversion performed is rather simple: null
, undefined
and false
become an empty array; any object featuring an explicit toArray
method (as many Prototype objects do) has it invoked; otherwise, we assume the argument "looks like an array" (e.g. features a length
property and the []
operator), and iterate over its components in the usual way.
When passed an array, $A
makes a copy of that array and returns it.
本文转自sucre03 51CTO博客,原文链接:http://blog.51cto.com/sucre/410388,如需转载请自行联系原作者