首页 > 解决方案 > 如何使用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))

这个问题有什么解决办法吗?

标签: javascriptarraysflatten

解决方案


问题是,当迭代外部数组时,条件

Array.isArray(currVal)

被满足,所以

accumArr.concat(currVal.map(childrenSelector))

运行时currVal是一个数字数组。但是数字没有.slice方法。

相反,调用childrenSelector, currValwithout .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))
);


推荐阅读