我正在尝试创建一个简单的函数来使用ES5对数组进行深度展平。我下面的方法是可行的,但似乎不是最优的,因为res
结果数组保存在What函数之外。
var arr = [1, 2, [3], [4, [5, [6, 7, 8, 9, 10, 11]]]]
, res = [];
function flatten(item){
if (Array.isArray(item)) {
item.forEach(el => {
return flatten(el, res);
});
}else {
res.push(item);
}
}
flatten(arr);
console.log(res); //[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
像生活这样的东西看起来很接近:
function flatten(item){
var res = [];
return (function(ress){
if (Array.isArray(item)) {
item.forEach(el => {
return flatten(el);
});
}else {
res.push(item);
}
})(res);
}
但是我没有完全理解它,因为res
在这里是未定义的。理想情况下,我希望函数的最后一行返回res
,这样函数就可以像var f = flatten(arr)
一样使用。
注意:
*这个问题不是专门关于如何深度展平数组的,因为有很多关于这个问题的答案。我真正感兴趣的是如何在这个实例中将results变量保留在父函数中。
https://stackoverflow.com/questions/41352997
复制相似问题