map 跟 forEach 遍历数组的区别

map() 跟forEach() 遍历数组的区别

区别 forEach没有返回值 只是它原有的数组的基础上进行修改
map 的话只是修改了他的返回值 并没有影响原数组

var array = [1, 2, 3, 4, 5, 6, 7];
var res = array.map(item => {
    return item * 2
});
console.log(res);

console.log(array);

var array = [1, 2, 3, 4, 5, 6, 7];
var res = array.forEach(item => {
    return item * 2
});
console.log(res);
console.log(array);

控制台打印如下

//对应map() 方法
PS E:\XL\test> node '.\map&&foreach.js'
[
   2,  4,  6, 8,
  10, 12, 14
]
[
  1, 2, 3, 4,
  5, 6, 7
]


// 对应forEach() 方法
PS E:\XL\test> node '.\map&&foreach.js'
undefined
[
  1, 2, 3, 4,
  5, 6, 7
]


发布了25 篇原创文章 · 获赞 13 · 访问量 3195

猜你喜欢

转载自blog.csdn.net/weixin_42216818/article/details/103242627