繁体   English   中英

在getElementsByClassName的重新创建过程中,Array.prototype.slice.call如何工作?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM