能否请您告诉我为什么此代码无法正常工作?
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]
)
答案 0 :(得分:1)
您需要遍历子数组的所有元素,然后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]]]]));
答案 1 :(得分:-1)