js数组中的find、filter、forEach、map四个方法的详解和应用实例

find(): 返回通过测试数组的第一个元素的值

1 array.find(function(value, index, arr),thisValue)

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

返回值:返回符合测试条件的第一个数组元素的值,如果没有符合条件的则返回undefined。

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

find()方法为数组中的每个元素都调用一次函数执行,当数组中的元素在测试条件时返回true,find()返回符合条件的元素,之后的值不会再执行函数。如果没有符合条件的元素则返回undefined。

filter():创建一个新数组,新数组中的元素是泰国检查指定数组中符合条件的所有元素

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

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

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

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

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

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

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

返回值:返回一个新数组,数组中的元素为原始数组元素调用函数处理后的值

1  var arr = [1,2,3,4,5,6,7];
2  var ar = arr.map(function(elem){
3     return elem*4;
4  });
5  console.log(ar);//[4, 8, 12, 16, 20, 24, 28]

forEach(): 用于调用数组的每个元素,并将元素传递给回调函数

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

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

返回值:undefined

1 var arr = [1,2,3,4,5,6,7];
2  var sum = 0;
3  var ar = arr.forEach(function(elem){
4     sum+=elem*4;
5  });
6  console.log(ar);//undefined
7  console.log(arr);//[1,2,3,4,5,6,7]

forEach()返回值为undefined,里面即便有return语句,返回值依然是undefined

总结一下

find()方法主要用来返回数组中符合条件的第一个元素(没有的话返回undefined)

filter()方法主要用来筛选数组中符合条件的所有元素,并且放在一个新的数组中,如果没有,返回一个空数组

map()方法主要用来对数组中的元素调用函数进行处理,并且把处理结果放在一个新数组中返回(如果没有返回值,新数组中的每一个元素都为undefined)

forEach()方法也是用于对于数组中的每一个元素进行回调函数,但他没有返回值

 

原文地址:https://www.cnblogs.com/chailuG/p/10815977.html