Does forEach () support link binding?

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

As in the code above, I noticed that changing the value of the element passed to the callback forEach()does not change the iterative object.

Use for...incertainly does.

Why is this and how do I change the values ​​in an array?

I find the topic covered quite confusing on MDN

+4
source share
3 answers

Use for ... in particular, does.

No no. Your cycle is forEachequivalent to this cycle for...in(except for the order):

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

, ? , JavaScript pass-by-value, , :

.

, item arr. , , , ..

arr[index] = 'foo';
+6

, forEach . - , - . , .

+4

In your case, a variable itemis passed by value because it has a primitive value. If it were a json object, and you would change one of its properties, this would be reflected in the original list.

In this situation, you can use other arguments that it has forEach. For instance:

arr.forEach(element, index, array) {
    ...
}

Using these arguments, you can directly influence array[index]

+1
source

Source: https://habr.com/ru/post/1542717/


All Articles