[英]How does Array.prototype.slice.call work in this recreation of getElementsByClassName?
我有一段我最了解的代碼。 我唯一不了解的是Array.prototype.slice.call在這種情況下的工作方式。
var getElementsByClassName = function(className){
var elements = $('*').filter(function(index, node){
// this will basically iterate through all nodes on the
// DOM and check to see which node matches the className passed in.
return $(node).hasClass(className);
});
// elements is an array of two elements. array[0] seems to be the non-enumerable
// properties (but it has a length property?) and the other is the element on the dom.
// the usage below slices out array[0] and returns array[1], but since both
// have a length property and numeric indices, why doesn't this usage return
// both items?
return Array.prototype.slice.call(elements);
};
我已經在線發表了我的評論/問題。 任何幫助將不勝感激:)。
謝謝,乙
您的代碼將構建一個jQuery對象,該對象僅包含具有搜索類的DOM節點。 對.slice()
的調用只是復制了該副本。 只是稍微簡單一點
return elements.get();
會做同樣的事情。 (當然, $("." + className)
將替換整個內容。)
jQuery對象不是數組。 它們是用來模擬數組的,而.slice()
方法並不挑剔。 只要它正在處理的對象具有length
方法和數字索引屬性(jQuery對象即可),就可以了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.