zoukankan      html  css  js  c++  java
  • [笔记]JS flat and flatMap

    原文
    flat()接收一个数组(这个数组中的某些item本身也是一个数组),返回一个新的一维数组(如果没有特别指定depth参数的话返回一维数组)。

    const nestedArraysOhMy = [ "a", ["b", "c"], ["d", ["e", "f"]]];
    // .flat() 接收一个可选的深度参数
    const ahhThatsBetter = nestedArraysOhMy.flat( 2 );
    console.log( ahhThatsBetter ); // [ "a", "b", "c", "d", "e", "f" ]
    

    flatMap()类似于map(),但是它的callback返回的是扁平的一维数组(如果没有特别指定depth参数的话)。

    const scattered = [ "my favorite", "hamburger", "is a", "chicken sandwich" ];
    
    // map() 返回的是嵌套的数组results in nested arrays
    const huh = scattered.map( chunk => chunk.split( " " ) );
    console.log( huh ); // [ [ "my", "favorite" ], [ "hamburger" ], [ "is", "a" ], [ "chicken", "sandwich" ] ]
    
    const better = scattered.flatMap( chunk => chunk.split( " " ) );
    console.log( better ); // [ "my", "favorite", "hamburger", "is", "a", "chicken", "sandwich" ]
    
  • 相关阅读:
    2、基础知识点回顾
    jQuery事件二
    71、auth模块、bbs项目关系表
    PYthon-4.26作业
    PYthon-线程
    PYthon-4.23作业
    PYthon-4.15作业
    PYthon-4.9作业
    PYthon-4.7作业
    PYthon-3.31作业
  • 原文地址:https://www.cnblogs.com/irocker/p/js-flat-flatmap.html
Copyright © 2011-2022 走看看