美文网首页
JavaScript中的flatMap

JavaScript中的flatMap

作者: 如果俞天阳会飞 | 来源:发表于2023-01-09 14:38 被阅读0次

flatMap

JavaScript Array flatMap()方法首页使用映射函数映射每个元素,然后将其展平为新数组

语法

arr.flatMap(callback(currentValue),thisArg)
  • callback 每个数组元素上执行的函数
  • thisArg (可选) callback时用作this值

注意事项

flatMap 方法不会改变原数组
flatMap 方法等效于 array.map().flat()

实例

  const arr1 = [1, 2, 3, 4, 5];
  const n1 = arr1.flatMap((x) => [x ** 2]);
  console.log(n1); // [1, 4, 9, 16, 25]
  const n2 = arr1.map((x) => [x ** 2]);
  console.log(n2); // [[1],[4],[9],[16],[25]]
  console.log(n2.flat()); // [1, 4, 9, 16, 25]

相关文章

网友评论

      本文标题:JavaScript中的flatMap

      本文链接:https://www.haomeiwen.com/subject/pwopcdtx.html