86-数组高级API-数组的过滤和映射

  • 数组的过滤

    • 数组的 filter 方法
      • 作用: 将满足条件的元素添加到一个新的数组中

          //         0  1  2  3  4
          let arr = [1, 2, 3, 4, 5];
          // 需求: 将这个数组中是偶数的元素添加到一个新的数组中
        
          let newArray = arr.filter(function (currentValue, currentIndex, currentArray) {
              if (currentValue % 2 === 0){
                  return true;
              }
          });
          console.log(newArray);  // [2, 4]
        
  • 数组的映射

    • 数组的 map 方法
      • 作用: 将满足条件的元素映射到一个新的数组中

          //         0  1  2  3  4
          let arr = [1, 2, 3, 4, 5];
          // 需求: 将这个数组中是偶数的元素添加到一个新的数组中
        
          // 数组的map方法会新建一个和当前数组一模一样的数组, 并且将里面的元素全部设置为undefined
          // 接下来只要有满足条件的元素就会把这个元素放到这个元素对应索引的位置, 将以前的undefined覆盖掉
          let newArray = arr.map(function (currentValue, currentIndex, currentArray) {
              if (currentValue % 2 === 0){
                  return currentValue;
              }
          });
          console.log(newArray);  // [undefined, 2, undefined, 4, undefined]
        
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容