简体   繁体   English

有人可以在这里解释“push”是怎么回事吗?

[英]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.

相关问题 精通 Javascript 的人可以简单地向我解释这里发生了什么 - Can someone fluent in Javascript explain to me whats going on here SIMPLY 有人能解释一下这里发生了什么吗? const {a={}}=b - Can some one explain what's going on here? const {a={}}=b 有人可以解释这里发生的步骤流程吗? - Can someone explain the flow of steps that are happening here? 请有人解释第二个方括号符号在这里做什么? - Please can someone explain what the second square bracket notation is doing here? 有人可以用简单的英语解释我的对象代码中特定部分的情况吗? - Can someone please explain in plain english what is going on in a particular part of my code for objects? 任何人都可以从类型强制、IIFE 和闭包方面解释这里发生的事情吗? - Can anybody explain what is going on here in terms of type coercion, IIFE, and closures? 有人可以向我解释适用于此的 JavaScript 中的规则吗? - Can someone explain to me the rule in JavaScript that applies here? 有人可以向我解释在这里如何调用for-in循环3次? - Can someone explain to me how the for-in loop is called 3 times here? 有人可以向我解释一下循环是如何在这里工作的吗? - Can someone explain to me how the loop works here? 有人能解释一下这个 ajax 代码的作用吗? - Can someone explain what this ajax code does?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM