如何使用 Javascript 中的给定回调来展平数组?

How to flatten array with the given callback in Javascript?

该函数必须将指定数组的每个元素投影到一个序列,并将生成的序列展平到一个数组中。

我的函数必须 return 基于给定选择器函数 (childrenSelector) 的展平数组,但在应用 slice() 函数时遇到问题。

当应用 slice 作为选择器函数时,它说

TypeError: x.slice is not a function

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 方法。

而是在 currVal 上调用 childrenSelector,而不调用 .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))
);