Prototype 學習 工具函數學習($A方法)_prototype

來源:互聯網
上載者:User
$A方法:
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.
複製代碼 代碼如下:

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;
}

如果傳進來的參數為null, undefined and false 則直接返回空數組
如果傳進來的參數對象裡有toArray方法,這直接調用參數的toArray方法,因為有許多Prototype對象裡面已經定義好了toArray方法,所以可以直接調用toArray方法
例如:
複製代碼 代碼如下:

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

接下來根據參數的length建立新數組,然後逐個把參數中的元素複製到新數組中去,最後返回新數組對象
下面給出prototype協助文檔的一段說明和例子也許更能說明這個函數的作用:
複製代碼 代碼如下:

/*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();

還有一點:
Array.from = $A;
數組對象的from靜態方法和$A是一個方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.