Does forEach() bind by reference?

后端 未结 3 1271
长发绾君心
长发绾君心 2020-12-20 11:57
var arr = [\'Foo\'];

arr.forEach(function(item){
  console.log(item);
  item = \'Lorem\';
  console.dir(arr[0]);

});

for (var item in arr){
  arr[item] = \'Ipsum\         


        
3条回答
  •  礼貌的吻别
    2020-12-20 12:47

    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';
    

提交回复
热议问题