forEach()是否通过引用绑定? [英] Does forEach() bind by reference?

查看:170
本文介绍了forEach()是否通过引用绑定?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  var arr = ['Foo']; 
$ b $ arr.forEach(function(item){
console.log(item);
item ='Lorem';
console.dir(arr [0] );

});

(arr中的var项){
arr [item] ='Ipsum';
console.dir(arr [0]);





$ b像上面显示的代码一样,我注意到改变了传递过来的值的值到 forEach()的回调不会导致迭代的对象改变。



中使用当然可以。



<为什么这个&我应该如何改变数组中的值?



我发现这个主题在 MDN 解决方案 div>


使用for ...当然可以。

不,不。你的 forEach 循环相当于这个 for ... in 循环(除了顺序):

  for(var index in arr){
var item = arr [index];
console.log(item);
item ='Lorem';
console.dir(arr [0]);
}

您是否看到数组未被修改?这是因为JavaScript始终是传递值 ,有一个非常简单的规则:


为变量赋值永不更改值

这意味着,将一个新值赋给 item ,不能更改 arr 的元素。如果你想修改数组,你必须直接通过赋值给一个索引来进行变异,即

$ $ $ $ $ $ $ $ $ ar $ [ index] ='foo';


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]);
}

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.

Using for...in certainly does.

Why is that & how should I alter values in an array?

I find that the topic is covered quite confusing on MDN

解决方案

Using for...in certainly does.

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]);
}

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.

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屋!

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