美文网首页
数组map和for Each方法的区别

数组map和for Each方法的区别

作者: 瓜田猹 | 来源:发表于2018-04-25 17:21 被阅读61次

相似点:都是用来遍历数组中的每一项值的,用来遍历数组中的每一项;
区别:forEach可以对对原来的数组产生改变
map的回调函数中支持return返回值,可以对原数组进行处理生成新的数组

1、forEach

语法: array.forEach(function(currentValue, index, arr), thisValue)

  • forEach() 方法用于调用数组的每个元素,并将元素传递给回调函数。
  • 注意: forEach() 对于空数组是不会执行回调函数的。
var res = ary.forEach(function (item,index,input) {
     input[index] = item*10;
})
console.log(res);//-->undefined;
console.log(ary);//-->会对原来的数组产生改变;

2、map

语法: array.map(function(currentValue,index,arr), thisValue)

  • map() 方法返回一个新数组,数组中的元素为原始数组元素调用函数处理后的值。
  • map() 方法按照原始数组元素顺序依次处理元素。
  • 注意: map() 不会对空数组进行检测。
  • 注意: map() 不会改变原始数组。
var ary = [12,23,24,42,1];
var res = ary.map(function (item,index,input) {
     return item*10;
})
console.log(res);//-->[120,230,240,420,10];//生成新的数组
console.log(ary);//-->[12,23,24,42,1];

相关文章

网友评论

      本文标题:数组map和for Each方法的区别

      本文链接:https://www.haomeiwen.com/subject/nuuylftx.html