javascript - 如何使用Javascript中的给定回调展平数组?
问题描述
该函数必须将指定数组的每个元素投影到一个序列中,并将生成的序列展平为一个数组。
我的函数必须根据给定的选择器函数 () 返回展平数组,但在应用函数childrenSelector
时遇到问题。slice()
当应用切片作为选择器函数时,它说
类型错误:x.slice 不是函数
function flattenArray(arr, childrenSelector) {
return arr.reduce((accumArr, currVal) => {
console.log(currVal);
return Array.isArray(currVal)
? accumArr.concat(currVal.map(childrenSelector))
: accumArr.concat(childrenSelector(currVal))
}, []
);
}
flattenArray([[11, 12, 13, 14, 15], [21, 22, ,23, 24, 25], [31, 32, 34, 35]], x => x.slice(0, 2))
这个问题有什么解决办法吗?
解决方案
问题是,当迭代外部数组时,条件
Array.isArray(currVal)
被满足,所以
accumArr.concat(currVal.map(childrenSelector))
运行时currVal
是一个数字数组。但是数字没有.slice
方法。
相反,调用childrenSelector
, currVal
without .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))
);
推荐阅读
- javascript - 如何在小游戏中记录 MAX SCORE 或个人最佳得分
- typescript - Typescript 和 Linter 如何解决和确定消息后的最佳打字:变量在分配之前设置?
- mlflow - 在没有 start_run 上下文管理器的情况下,无法在 pytorch 闪电中使用 mlflow.pytorch.save_model
- javascript - 单击按钮不适用于 asp.net 部分页面中的 div
- assembly - 使用 ATA/IDE PIO 读取磁盘扇区时出现奇怪的数据
- xml - 重定向到外部 URL 而不是 XML 响应
- c# - End Of Central Directory 中预期的条目数与 Central Directory 中的条目数不对应
- javascript - 如何用 \n 美化 json?
- javascript - P5JS 中的二维布尔数组作为成员变量
- python - 检索数据的 ValueError DataFrame.dtypes 必须是 int、float 或 bool