Skip to content

flat 和 flatMap #4

Description

@ycshill

今天分享一个ECMAScript的continuous,文章最下面附了原文链接。
文章的题目:“Flatten Arrays in Vanilla JavaScript with flat() and flatMap()”很好的解释了flat()flatMap()的作用,就是用来 展开数组,并且是不用任何第三方库;直接上例子

flat()

  • 简单的例子
const animals = [['🐕', '🐶'], ['😺', '🐈']];

const flatAnimals = animals.flat();
// same as: const flatAnimals = animals.flat(1);

console.log(flatAnimals);

// ['🐕', '🐶', '😺', '🐈']
  • 当数组的总的深度大于flat()方法的深度的时候:
const animals = [['🐕', '🐶'], ['😺', '🐈', ['😿',['🦁'], '😻']]];

const flatAnimals = animals.flat(2);

console.log(flatAnimals);
// ['🐕', '🐶', '😺', '🐈', '😿',['🦁'], '😻']
  • 如果你想要展开任意的数组的话,可以给flat的参数设置为Infinity
const animals = [['🐕', '🐶'], ['😺', '🐈', ['😿',['🦁'], '😻']]];

const flatAnimals = animals.flat(Infinity);

console.log(flatAnimals);
// ['🐕', '🐶', '😺', '🐈', '😿', '🦁', '😻']

flatMap()

flatMap() 就是对数组的每个值先执行map方法,然后再对形成的数组执行flat(1)的方法;

const animals = ['🐕', '🐈', '🐑', '🐮'];
const noises = ['woof', 'meow', 'baa', 'mooo'];

const mappedOnly = animals.map((animal, index) => [animal, noises[index]]);
const mappedAndFlatten = animals.flatMap((animal, index) => [animal, noises[index]]);

console.log(mappedOnly);
// [['🐕', 'woof'], ['🐈', 'meow'], ['🐑', 'baa'], ['🐮', 'mooo']

console.log(mappedAndFlatten);
// ['🐕', 'woof', '🐈', 'meow', '🐑', 'baa', '🐮', 'mooo']

原文地址的链接

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions