JavaScript:.forEach() 和 .map() 之间的区别 [英] JavaScript: Difference between .forEach() and .map()

查看:29
本文介绍了JavaScript:.forEach() 和 .map() 之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道有很多这样的话题.我知道基础知识:.forEach() 对原始数组进行操作,.map() 对新数组进行操作.

I know that there were a lot of topics like this. And I know the basics: .forEach() operates on original array and .map() on the new one.

就我而言:

function practice (i){
    return i+1;
};

var a = [ -1, 0, 1, 2, 3, 4, 5 ];
var b = [ 0 ];
var c = [ 0 ];
console.log(a);
b = a.forEach(practice);
console.log("=====");
console.log(a);
console.log(b);
c = a.map(practice);
console.log("=====");
console.log(a);
console.log(c);

这是输出:

[ -1, 0, 1, 2, 3, 4, 5 ]
=====
[ -1, 0, 1, 2, 3, 4, 5 ]
undefined
=====
[ -1, 0, 1, 2, 3, 4, 5 ]
[ 0, 1, 2, 3, 4, 5, 6 ]

我不明白为什么使用 practice 会将 b 的值更改为 undefined.
如果这是一个愚蠢的问题,我很抱歉,但我对这种语言很陌生,到目前为止我找到的答案并没有让我满意.

I can't understand why using practice changes value of b to undefined.
I'm sorry if this is silly question, but I'm quite new in this language and answers I found so far didn't satisfy me.

推荐答案

它们不是一回事.让我解释一下区别.

They are not one and the same. Let me explain the difference.

forEach:它遍历一个列表,并对每个列表成员应用一些带有副作用的操作(例如:将每个列表项保存到数据库中)并且不返回任何内容.

forEach: This iterates over a list and applies some operation with side effects to each list member (example: saving every list item to the database) and does not return anything.

map:这将迭代一个列表,转换该列表的每个成员,并返回另一个具有转换成员的相同大小的列表(例如:将字符串列表转换为大写).它不会改变调用它的数组(尽管如果传递一个回调函数,它可能会这样做).

map: This iterates over a list, transforms each member of that list, and returns another list of the same size with the transformed members (example: transforming list of strings to uppercase). It does not mutate the array on which it is called (although if passed a callback function, it may do so).

参考资料

Array.prototype.forEach() -JavaScript |MDN

Array.prototype.map() -JavaScript |MDN

这篇关于JavaScript:.forEach() 和 .map() 之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆