且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

prototype中的$A函数的用法

更新时间:2022-09-25 08:26:14



  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,如需转载请自行联系原作者