prototype中的$A函数的用法


 
  
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
  2.  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
  3. <html> 
  4. <head> 
  5.     <title>$A</title> 
  6.     <script language="javascript" src="prototype.js" 
  7.      type="text/javascript"></script> 
  8.     <script language="javascript" type="text/javascript"> 
  9.     function showOptions() { 
  10.         //先获取id为listFramework的对象,再由对象找到tagName为option的内容 
  11.         var someNodeList = $("lstFramework").getElementsByTagName("option"); 
  12.         var nodes = $A(someNodeList); 
  13.          
  14.         var info = []; 
  15.          
  16.         nodes.each (function(node){ 
  17.             info.push(node.value + ": " + node.innerHTML); 
  18.         }); 
  19.          
  20.         alert(info.join("\r\n")); 
  21.     } 
  22.     </script> 
  23. </head> 
  24. <body> 
  25.     <form> 
  26.         <select id="lstFramework" size="10"> 
  27.             <option value="1">Prototype</option> 
  28.             <option value="2">Script.aculo.us</option> 
  29.             <option value="3">Dojo</option> 
  30.             <option value="4">YUI</option> 
  31.         </select> 
  32.         <input onclick="showOptions();" type="button" value="Show the options"> 
  33.     </form> 
  34. </body> 
  35. </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 Arrays trump any other collection type you might otherwise get.

The conversion performed is rather simple: nullundefined 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,如需转载请自行联系原作者


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值