js filter()、forEach()、map()的用法解析

时间:2020-05-29
本文章向大家介绍js filter()、forEach()、map()的用法解析,主要包括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]

原文地址:https://www.cnblogs.com/wangyingblock/p/12988708.html