[英]Can someone explain what is going on with `push` here?
It feels like push
is behaving funny.感觉push
的行为很有趣。 Rather than just push to 1 index inside the forEach
, it seems to be pushing to all 3 indexes.而不是仅仅推送到forEach
内的 1 个索引,它似乎正在推送到所有 3 个索引。 Am I missing something obvious?我错过了一些明显的东西吗?
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)
Expected output: [[1], [2], [3]]
预期 output: [[1], [2], [3]]
Actual output: [[1, 2, 3], [1, 2, 3], [1, 2, 3]]
实际 output: [[1, 2, 3], [1, 2, 3], [1, 2, 3]]
push
isn't the culprit, it is fill
. push
不是罪魁祸首,而是fill
。
You've created an array the same length as the original and then filled it with a value.您创建了一个与原始数组长度相同的数组,然后用一个值填充它。
That value is an array.该值是一个数组。
The same array.同一个数组。
So when you push a value to copied[0]
you get a reference to that array and put a value into it.因此,当您将一个值推送到copied[0]
时,您将获得对该数组的引用并将一个值放入其中。
And when you push a value to copied[1]
you get a reference to that same array and put another value into it.当您将一个值推送到copied[1]
时,您将获得对同一数组的引用并将另一个值放入其中。
let arr = [ [ 7, 3, 47 ] ]
let reduced = arr.flat().map(e=>[e])
console.log(reduced)
//output: [[7], [3], [47]] //输出:[[7],[3],[47]]
if you want your Expected output: [[1], [2], [3]]如果你想要你的预期 output: [[1], [2], [3]]
Simply return index instead of item in inner array只需返回索引而不是内部数组中的项目
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.