forEach() 是否通过引用绑定? [英] Does forEach() bind by reference?
问题描述
var arr = ['Foo'];
arr.forEach(function(item){
console.log(item);
item = 'Lorem';
console.dir(arr[0]);
});
for (var item in arr){
arr[item] = 'Ipsum';
console.dir(arr[0]);
}
如上面的代码所示,我注意到更改传递给 forEach()
回调的项的值不会导致迭代对象发生更改.
Like the code above shows, I noticed that changing the value of an item passed to the callback of forEach()
does not cause the iterated object to alter.
使用 for...in
当然可以.
为什么会这样 &我应该如何更改数组中的值?
我发现该主题在 MDN
推荐答案
使用 for...in 当然可以.
Using for...in certainly does.
不,不是.你的 forEach
循环相当于这个 for...in
循环(除了顺序):
No it doesn't. Your forEach
loop is equivalent to this for...in
loop (apart from the order):
for (var index in arr) {
var item = arr[index];
console.log(item);
item = 'Lorem';
console.dir(arr[0]);
}
你看到数组也没有被修改吗?这是因为 JavaScript 总是传值,并且有一个非常简单的规则要记住:
Do you see that the array isn't modified either? That's because JavaScript is always pass-by-value, and there is a very simple rule to keep in mind:
为变量赋值从不改变另一个变量或数据结构的值.
Assigning a value to a variable never changes the value of another variable or data structure.
这意味着,为item
分配一个新值,不能改变arr
的元素.如果你想修改数组,你必须通过给一个索引赋值来直接改变它,即
That means, assigning a new value to item
, cannot change an element of arr
. If you want to to modify the array, you have to mutate it directly by assigning a value to an index, i.e.
arr[index] = 'foo';
这篇关于forEach() 是否通过引用绑定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!