簡體   English   中英

有人可以在這里解釋“push”是怎么回事嗎?

[英]Can someone explain what is going on with `push` here?

感覺push的行為很有趣。 而不是僅僅推送到forEach內的 1 個索引,它似乎正在推送到所有 3 個索引。 我錯過了一些明顯的東西嗎?

 let arrayToReduce = [ [ 1, 2, 3 ] ] let reduced = arrayToReduce.reduce((arr, inner) => { const copied = arr.slice() inner.forEach((num, idx) => { copied[idx].push(num) }) return copied }, Array(arrayToReduce[0].length).fill([])) console.log(reduced)

預期 output: [[1], [2], [3]]

實際 output: [[1, 2, 3], [1, 2, 3], [1, 2, 3]]

push不是罪魁禍首,而是fill

您創建了一個與原始數組長度相同的數組,然后用一個值填充它。

該值是一個數組。

同一個數組。

因此,當您將一個值推送到copied[0]時,您將獲得對該數組的引用並將一個值放入其中。

當您將一個值推送到copied[1]時,您將獲得對同一數組的引用並將另一個值放入其中。

    let arr = [ [ 7, 3, 47 ] ]
    let reduced = arr.flat().map(e=>[e])
    console.log(reduced) 

//輸出:[[7],[3],[47]]

如果你想要你的預期 output: [[1], [2], [3]]

只需返回索引而不是內部數組中的項目

    let arr = [ [ 7, 3, 47 ] ]
    let reduced = arr.flat().map((e,i)=>[i+1])
    console.log(reduced)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM