JavaScript:.forEach()和.map()之间的区别

编程入门 行业动态 更新时间:2024-10-22 07:16:31
本文介绍了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 ]

我无法理解为什么使用练习将 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)

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)

引用

数组.prototype.forEach() - JavaScript | MDN

Array.prototype.map() - JavaScript | MDN

更多推荐

JavaScript:.forEach()和.map()之间的区别

本文发布于:2023-11-26 00:19:25,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1631910.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:区别   JavaScript   forEach   map

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!