javascript - I push a value to an array in foreach, why does this result appear?
三叔
三叔 2017-06-30 09:55:03
0
2
1253
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

三叔
三叔

reply all (2)
女神的闺蜜爱上我

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

    phpcn_u1582

    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) })
      Latest Downloads
      More>
      Web Effects
      Website Source Code
      Website Materials
      Front End Template
      About us Disclaimer Sitemap
      php.cn:Public welfare online PHP training,Help PHP learners grow quickly!