执行 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<的值/code> 在每次调用回调中:
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()
中涉及的数组code> 调用可能是 this
的 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
检查数组中的所有条目是否与描述匹配;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屋!