今天分享一个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']
原文地址的链接
今天分享一个ECMAScript的continuous,文章最下面附了原文链接。
文章的题目:“Flatten Arrays in Vanilla JavaScript with flat() and flatMap()”很好的解释了
flat()和flatMap()的作用,就是用来 展开数组,并且是不用任何第三方库;直接上例子flat()
flat()方法的深度的时候:flat的参数设置为InfinityflatMap()
flatMap()就是对数组的每个值先执行map方法,然后再对形成的数组执行flat(1)的方法;原文地址的链接