正如标题所述,我尝试将 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) 步骤似乎失败了。:/
任何接受者都可以看到我缺少什么?:)