Does forEach() bind by reference?

后端 未结 3 1320
长发绾君心
长发绾君心 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:55

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

    In this situation, you can use other arguments that the forEach has. For example:

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

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

提交回复
热议问题