javascript - 使用递归展平数组内的数组
问题描述
你能告诉我为什么这段代码不能正常工作吗?
flatten 函数假设从输入数组中的任何数组中删除值并将这些值作为数组返回。
function flatten(arr) {
//create a new array
let newArr = [];
//create a helperFunction
function helperFunction(helperArr) {
//if its an empty array
if (helperArr.length === 0) {
return;
}
//get the first value from the array and remove the value
let firstArrVal = helperArr.shift();
let isAnArray = Array.isArray(firstArrVal);
//if value is an array
if (isAnArray) {
//call recursive function on value
return helperFunction(firstArrVal);
}
//if value isnt an array
else {
//add value to new array
newArr.push(firstArrVal);
//call recursive function on the array
return helperFunction(helperArr);
}
}
//call helperFunction
helperFunction(arr);
//return new array
return newArr;
}
console.log(flatten([1, [2, [3, 4],
[
[5]
]
]]));
// Correct output - [1, 2, 3, 4, 5] - Mine - [1, 2, 3, 4]
对于输入[1, [2, [3, 4], [[5]]]]
,正确的输出是[1, 2, 3, 4, 5]
(我的 - [1, 2, 3, 4]
)
解决方案
您需要遍历子数组的所有元素,并push
对其进行调用或调用helperFunction
。您当前的
let firstArrVal = helperArr.shift();
let isAnArray = Array.isArray(firstArrVal);
只会合并第一个嵌套值,但不会合并第 0 个之后的任何嵌套索引。for
对数组中的每个值使用循环:
function flatten(arr) {
//create a new array
let newArr = [];
//create a helperFunction
function helperFunction(helperArr) {
//if its an empty array
if (helperArr.length === 0) {
return;
}
for (let i = 0; i < helperArr.length; i++) {
const val = helperArr[i];
let isAnArray = Array.isArray(val);
//if value is an array
if (isAnArray) {
//call recursive function on value
helperFunction(val);
}
//if value isnt an array
else {
//add value to new array
newArr.push(val);
}
}
}
//call helperFunction
helperFunction(arr);
//return new array
return newArr;
}
console.log(flatten([1, [2, [3, 4],
[
[5]
]
]]));
或者,为了更简洁,使用flat
(为不兼容的浏览器添加一个polyfill):
const flatten = arr => arr.flat(Infinity);
console.log(flatten([1, [2, [3, 4],[[5]]]]));
推荐阅读
- c++ - GPS 将米转换为位移度
- python-3.x - pandas groupby nlargest 不允许查看所有数据 set_index 问题
- sql - 旧的 Mac 软件所以不能使用数据库 (Xcode)(SQL)
- python - 无法将时间对象转换为 datetime64[ns]
- angular - Angular 7 材质 | mat-select 按键上的自动填充在清除后不会重置源
- git - Gitkraken:隐藏文件夹中的所有分支
- ruby-on-rails - Rswag 和 Rspec:URL 参数的未定义方法
- python - 使用特征工具创建“时间窗口特征”
- amazon-web-services - maven settings.xml 拉环境变量?
- python - 有没有办法为新的 venv 升级 pip?