1 回答
TA贡献1982条经验 获得超2个赞
问题是,当迭代外部数组时,条件
Array.isArray(currVal)
满足,所以
accumArr.concat(currVal.map(childrenSelector))
运行 whencurrVal是一个数字数组。但是数字没有.slice方法。
相反,呼叫childrenSelector上currVal,没有.map(使得阵列切片):
function flattenArray(arr, childrenSelector) {
return arr.reduce((accumArr, currVal) => {
return accumArr.concat(childrenSelector(currVal));
}, []);
}
console.log(
flattenArray([
[11, 12, 13, 14, 15],
[21, 22, , 23, 24, 25],
[31, 32, 34, 35]
], x => x.slice(0, 2))
);
您还可以使用flatMap:
const flattenArray = (arr, childrenSelector) => arr.flatMap(childrenSelector);
console.log(
flattenArray([
[11, 12, 13, 14, 15],
[21, 22, , 23, 24, 25],
[31, 32, 34, 35]
], x => x.slice(0, 2))
);
添加回答
举报