javascript - 尝试重写 getElementByClassName,遇到递归快照

标签 javascript

正如标题所提到的,我尝试重写 getElementByClassName 作为个人练习,但在递归返回结果时遇到了一些意外的行为。

Document.prototype.getElementsByClassNameExercise = function(className, tempElement){
  var currentElement = (tempElement || document),
    children = currentElement.childNodes,
    results = [],
    classes = [];

  // Loop through children of said element
  for(var i =0;i<children.length;i++){    
    if(children[i].className && children[i].className !== '') {
      classes = children[i].className.split(' ');

      // Important to note, forEach is not ie8 safe.
      classes.forEach(function(singleClass){
        if(singleClass === className) {
          results.push(children[i]);
        }
      });
    }
    results.concat(Document.prototype.getElementsByClassNameExercise.call(this,     className, children[i]));
  }

  return results;
}

我在主页上尝试了此操作,它似乎成功解析了所有 DOM 元素并找到了 className...但 return/results.concat(results) 步骤似乎失败了。 :/

任何接受者都可以看到我错过了什么吗? :)

最佳答案

你的问题

你并没有错过太多。

concat()返回一个新数组,如其 MDN 中所述文章:

Summary

Returns a new array comprised of this array joined with other array(s) and/or value(s).

Description

[...] concat does not alter this or any of the arrays provided as arguments but instead returns a shallow copy that contains copies of the same elements combined from the original arrays.

如有疑问,您也可以随时引用ECMA-262 specs如果 MDN 还不够,请参阅第 15.4.4.4 节:

When the concat method is called with zero or more arguments item1, item2, etc., it returns an array containing the array elements of the object followed by the array elements of each argument in order.

解决方案

您需要重新分配结果变量。

更改此行:

results.concat(Document.prototype.getElementsByClassNameExercise.call(this,     className, children[i]));

至:

results = results.concat(Document.prototype.getElementsByClassNameExercise.call(this,     className, children[i]));

关于javascript - 尝试重写 getElementByClassName,遇到递归快照,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18629396/

相关文章:

javascript - 获取位于隐藏父级的元素的尺寸

javascript - 追加数组项或排除(如果已存在)

javascript - JQuery从Json文件中读取

javascript - 无法通过 SoundCloud 进行身份验证,登录回调正在尝试访问跨域框架

javascript - 用于记住下拉选择的 cookie

javascript - 使用 lazysizes 延迟加载背景图像

javascript - 克隆后 div 内的按钮不起作用

javascript - 谷歌地图 API 和 IE6

javascript - Flexslider和Fancybox可以在同一个页面使用吗?

javascript - children 在 react parent 中输入 Action