正如标题所提到的,我尝试重写 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) 步骤似乎失败了。 :/
任何接受者都可以看到我错过了什么吗? :)
最佳答案
你的问题
你并没有错过太多。
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/