在进行foreach时更改数组中的值 [英] change values in array when doing foreach

查看:135
本文介绍了在进行foreach时更改数组中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

示例:

var arr = ["one","two","three"];

arr.forEach(function(part){
  part = "four";
  return "four";
})

alert(arr);

该数组仍保留其原始值,是否有任何方法可以从迭代函数对数组元素进行写访问?

The array is still with it's original values, is there any way to have writing access to array's elements from iterating function ?

推荐答案

回调传递给元素,索引和数组本身.

The callback is passed the element, the index, and the array itself.

arr.forEach(function(part, index, theArray) {
  theArray[index] = "hello world";
});

edit -如注释中所述,.forEach()函数可以采用第二个参数,该参数将在每次对回调的调用中用作this的值:

edit — as noted in a comment, the .forEach() function can take a second argument, which will be used as the value of this in each call to the callback:

arr.forEach(function(part, index) {
  this[index] = "hello world";
}, arr); // use arr as this

第二个示例显示arr本身在回调中被设置为this.可能认为.forEach()调用所涉及的数组可能是 default 值,但无论出于什么原因,它都不是;如果未提供第二个参数,则this将为undefined.

That second example shows arr itself being set up as this in the callback.One might think that the array involved in the .forEach() call might be the default value of this, but for whatever reason it's not; this will be undefined if that second argument is not provided.

(注意:如果回调是=>函数,则上述有关this的内容将不适用,因为调用这些函数时this从未绑定任何东西.)

(Note: the above stuff about this does not apply if the callback is a => function, because this is never bound to anything when such functions are invoked.)

同样重要的是要记住,Array原型上提供了一整套类似的实用程序,并且在Stackoverflow上弹出了有关一个或另一个功能的许多问题,因此最好的解决方案是简单地选择其他工具.您已经:

Also it's important to remember that there is a whole family of similar utilities provided on the Array prototype, and many questions pop up on Stackoverflow about one function or another such that the best solution is to simply pick a different tool. You've got:

  • forEach用于处理数组中的每个条目或对其进行操作;
  • filter用于生成仅包含合格条目的新数组;
  • map用于通过转换现有数组来制作一对一的新数组;
  • some检查数组中至少一个元素是否符合某些描述;
  • every检查数组中的 all 条目是否与描述匹配;
  • find在数组中查找值
  • forEach for doing a thing with or to every entry in an array;
  • filter for producing a new array containing only qualifying entries;
  • map for making a one-to-one new array by transforming an existing array;
  • some to check whether at least one element in an array fits some description;
  • every to check whether all entries in an array match a description;
  • find to look for a value in an array

,依此类推. MDN链接

这篇关于在进行foreach时更改数组中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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