JS forEach replaces the elements in the array

JS forEach replaces the elements in the array

let arr = [
  {   name: '1',
      id: '1'
  },{ name: '2',
      id: '2'
  },{   name: '3',
      id: '3'
  }
]

arr.forEach(list=>{
  if(list.name==='2'){
    list = {a: 'hee'}
  }
})
console.log(arr)

To be reasonable, the first reaction should output:

[[object Object] {
  id: "1",
  name: "1"
}, [object Object] {
  a: "hee"
}, [object Object] {
  id: "3",
  name: "3"
}]

However, it backfired, and the output turned out to be:

[[object Object] {
  id: "1",
  name: "1"
}, [object Object] {
  id: "2",
  name: "2"
}, [object Object] {
  id: "3",
  name: "3"
}]

That is, the found name === '2'list is not replaced.

Why?

Here, in fact, list is a newly created variable that points to an item in the arr array. When we assign list = {a: 'hee'}a value, we just change the pointer of the list variable; nothing in the arr element is changed. So, nothing in arr is changed.

How to change it?

Then, by directly changing the elements in the object pointed to by list, you can change the elements in arr:

let arr = [
  {   name: '1',
      id: '1'
  },{ name: '2',
      id: '2'
  },{   name: '3',
      id: '3'
  }
]
arr.forEach(list=>{
  if(list.name==='2'){
    list.name = 'zding'
  }
})

console.log(arr)

This gives the desired output:

[[object Object] {
  id: "1",
  name: "1"
}, [object Object] {
  id: "2",
  name: "zding"
}, [object Object] {
  id: "3",
  name: "3"
}]

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324828677&siteId=291194637