在进行foreach时更改数组中的值 [英] change values in array when doing 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()
调用所涉及的数组可能是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屋!