[英]Can someone fluent in Javascript explain to me whats going on here SIMPLY
[英]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.