首頁  >  問答  >  主體

javascript - 我在foreach裡給一個array push值,為什麼會出現這樣的結果

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

得出的結果是

[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網址
https://jsbin.com/papamadejo/...
我想知道為什麼會是這樣的結果
不應該是[1,2,3,4,5]麼

三叔三叔2670 天前1289

全部回覆(2)我來回復

  • 女神的闺蜜爱上我

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

    foreach中arr變數重名了,因此操作了arr2。
    把第三個參數(arr)刪除

    回覆
    0
  • phpcn_u1582

    phpcn_u15822017-06-30 09:57:03

    就是這樣的,你可以參考一哈mdn上的說明:

    這段程式碼中的

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

    arr指向的是arr2.

    可以做以下修改

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

    回覆
    0
  • 取消回覆