数组降维

77 阅读1分钟

flat、flatMap

const arr = [1, 2, 3, [4, 5], 6, 7, [[8, 9], [10, 11], 12], 13];

// 默认降维1层
console.log(arr.flat());
// 指定降维层
console.log(arr.flat(2));

const names = ['Shark dog', 'Su su', '土 狗'];

const words = names.flatMap(item => {
    // 返回的本来是个数组但自动被降维了([[Shark, dog],[Su, su],[土, 狗]])
    return item.split(' ');
});
// 所以这里省去了再次降维
console.log(words);