zoukankan      html  css  js  c++  java
  • js filter()、forEach()、map()的用法解析

    最近进行前端开发时使用到了filter()、forEach()、map()方法,这里介绍一下它们的大致用法:

    1、filter()是通过删选oldArray,来生产newArray的方法

    语法:

    array.filter(function(value, index, arr),thisValue)
    

    value:必须,代表当前元素,其他四个参数都是可选,index代表当前索引值,arr代表当前的数组,thisValue代表传递给函数的值,一般用this值,如果这个参数为空,undefined会传递给this值

    返回值:返回数组,包含了符合条件的所有元素,如果没有符合条件的则返回空数组

    用法:

    var arr = [1,2,3,4,5,6,7];
     var ar = arr.filter(function(elem){
         return elem>5;
     });
     console.log(ar);//[6,7]
    

    简单用法:

    var arr = [1,2,3,4,5,6,7];
     var ar = arr.filter(elem => {
         return elem>5;
     });
     console.log(ar);//[6,7]
    

    2、forEach()用于遍历数组中的每个元素,并将元素传递给回调函数。它没有返回值,直接修改原数组中的数据。跟for循环用法类似。

    语法:

    array.forEach(function(value, index, arr),thisValue)
    

    value:必须,代表当前元素,其他四个参数都是可选,index代表当前索引值,arr代表当前的数组,thisValue代表传递给函数的值,一般用this值,如果这个参数为空,undefined会传递给this值。

    用法:

    let arr = [
      {   name: '1',
          id: '1'
      },{ name: '2',
          id: '2'
      },{   name: '3',
          id: '3'
      }
    ]
    arr.forEach(item=>{
      if(item.name==='2'){
        item.name = 'zding'
      }
    })
    
    console.log(arr)
     [
      {   name: '1',
          id: '1'
      },{ name: 'zding',
          id: '2'
      },{   name: '3',
          id: '3'
      }
    ]
    
    

    它没有产生新的数组,修改的是原来的数组。

    当数组中为单类型数据时:string、int等类型,这种方式的修改就不起作用了

    例如:

    let arr = [1,3,5,7,9]
    arr.forEach(function(item){
            item = 30
     })
    console.log(arr)  //输出  [1, 3, 5, 7, 9]        
    

    我们期望输输出 [30, 30, 30, 30, 30],但实际上输出为 [1, 3, 5, 7, 9],修改没有起作用。

    这个时候我们可以使用for循环,或者map()方法。

    map()返回一个新数组,数组中的元素为原始数组元素调用函数处理后的值,map()方法按照原始数组元素顺序依次处理元素.

    语法:

    array.map(function(value, index, arr),thisValue)
    

    用法:

    var arr = [1,2,3,4,5,6,7];
     var ar = arr.map(function(elem){
        return elem*4;
     });
     console.log(ar);//[4, 8, 12, 16, 20, 24, 28]
    console.log(arr);//[1,2,3,4,5,6,7]
    
    
  • 相关阅读:
    源码阅读(18):Java中主要的Map结构——HashMap容器(中)
    源码阅读(17):红黑树在Java中的实现和应用
    java中创建文件并写入的方法
    源码阅读(16):Java中主要的Map结构——HashMap容器(上)
    源码阅读(15):Java中主要的Map结构——概述
    从源码分析:Java中的AQS
    源码阅读(14):Java中主要的Queue、Deque结构——PriorityQueue集合(下)
    源码阅读(13):Java中主要的Queue、Deque结构——PriorityQueue集合(中)
    java 归并排序与快速排序
    python中的容器、可迭代对象、迭代器、生成器
  • 原文地址:https://www.cnblogs.com/wangyingblock/p/12988708.html
Copyright © 2011-2022 走看看