简体   繁体   English

如何使用 JavaScript 的 forEach 来修改数组的内容?

[英]How do you use JavaScript's forEach to modify the contents of an array?

给定一个 JavaScript 数组,如何使用forEach运算符修改数组中的项?

This is a simple question, but I'm posting the answer so I don't have to figure it out from scratch again.这是一个简单的问题,但我发布了答案,因此我不必再次从头开始弄清楚。 The function called by forEach takes three parameters, the current item, the index of that item, and the array object. forEach调用的函数接受三个参数,当前项、该项的索引和数组对象。 So, using a => style function, the solution is:因此,使用=>样式函数,解决方案是:

var data = [1,2,3,4];
data.forEach( (item, i, self) => self[i] = item + 10 );

gives the result:给出结果:

[11,12,13,14]

The self parameter isn't strictly necessary with the arrow style function, so self参数对于箭头样式函数并不是绝对必要的,所以

data.forEach( (item,i) => data[i] = item + 10);

also works.也有效。 You also get the same result using a regular function, eg:您还可以使用常规函数获得相同的结果,例如:

data.forEach( function(item, i, self) { self[i] = item + 10; } );

If you're replacing array items, a better way to do this is to use map instead:如果要替换数组项,更好的方法是改用map

var data = [1, 2, 3, 4];
data = data.map(item => item + 10);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM