Home  >  Q&A  >  body text

javascript - I push a value to an array in foreach, why does this result appear?

let arr = []
arr.push(1)
let arr2 = [2,3,4,5]
arr2.forEach((item,index,arr)=>{
    arr.push(item)
  console.log(arr)
})

The result is

[2, 3, 4, 5, 2]
[2, 3, 4, 5, 2, 3]
[2, 3, 4, 5, 2, 3, 4]
[2, 3, 4, 5, 2, 3, 4, 5]

jsbin address
https://jsbin.com/papamadejo/...
I want to know why this is the result
It shouldn’t be [1,2,3,4,5] What

三叔三叔2670 days ago1280

reply all(2)I'll reply

  • 女神的闺蜜爱上我

    女神的闺蜜爱上我2017-06-30 09:57:03

    The arr variable in foreach has the same name, so arr2 is operated.
    Delete the third parameter (arr)

    reply
    0
  • phpcn_u1582

    phpcn_u15822017-06-30 09:57:03

    That’s it, you can refer to the instructions on Yiha mdn:

    in this code
    arr2.forEach((item,index,arr)=>{
        arr.push(item)
      console.log(arr)
    })
    

    arr points to arr2.

    You can make the following modifications

    let arr1 = []
    arr.push(1)
    let arr2 = [2,3,4,5]
    arr2.forEach((item,index)=>{
        arr1.push(item)
      console.log(arr1)
    })
    

    reply
    0
  • Cancelreply