我已经编写了一个下划线_.flatten函数的版本,它可以工作,但我不明白为什么第一个工作但不是第二个版本。
var flatten = function (array, result) {
var result = [];
for (var i = 0; i < array.length; i++) {
var current = array[i];
if (Array.isArray(current)) {
result.push.apply(array, flatten(current));
}
else {
result.push(current);
}
}
return result;
};
var nested = [1, [2], [3, [[[4]]]]];
console.log(flatten(nested));
// [1,2,3,4]
VS
var flatten = function (array, result) {
var result = [];
array.forEach(function (current) {
if (Array.isArray(current)) {
result.push.apply(array, flatten(current));
}
else {
result.push(current);
}
});
return result;
};
var nested = [1, [2], [3, [[[4]]]]];
console.log(flatten(nested));
// [1]