我正在查看 JS 练习代码(用于面试),我看到讲师在函数参数中使用/分配了空数组
function walk(collection, result = []) {
collection.forEach(item => {
if(isTheItem(item)) result.push(item);
else walk(item[0].children, result);
});
return result;
}
一般来说,上面的代码和下面的代码是等价的吗
function walk(collection) {
const result = []
collection.forEach(item => {
if(isTheItem(item)) result.push(item);
else walk(item[0].children, result);
});
return result;
}
即使从递归的 Angular 来看?如果不是,有人可以向我解释一下区别吗?
最佳答案
is the above code and the following code equal
不,因为在你的第二个代码中,walk
只接受一个参数,并且每次调用walk
(无论是否递归)都会有一个新的结果
。您的第二个代码当前仅输出集合中顶层的项目。
要修复第二个代码,您必须接受第二个参数来传递结果
,例如:
function walk(collection, result) {
if (!result) {
result = [];
}
collection.forEach(item => {
if(isTheItem(item)) result.push(item);
else walk(item[0].children, result);
});
return result;
}
关于javascript - 在函数参数中设置空数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56002029/