这似乎很简单,但我无法正常工作。我想做的是从数组中获取项目,并将它们一个一地分发到嵌套数组中。这是我的代码:
const numbers = [1, 2, 3, 4, 5, 6, 7, 8]
const nestedArray = Array(numberOfSlots).fill([])
_.forEach(numbers, (number, index) => {
console.log('index', index);
nestedArray[index % numberOfSlots].push(number)
console.log('nested Array', nestedArray)```
What I expected to see was something like this:
iteration 1: `[[1][][][][]`
iteration 2: `[[1][2][][][]`
iteration 3: `[[1][2][3][][]`
iteration 4: `[[1][2][3][4][]`
iteration 5: `[[1][2][3][4][5]`
iteration 6: `[[1, 6][2][3][4][5]`
iteration 7: `[[1, 6][2, 7][3][4][5]`
iteration 8: `[[1, 6][2, 7][3, 8][4][5]`
but what I get is this:
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/xYH2m.png
Why is this happening? As best I can tell it adds every item to every sub-array on each pass instead of only the array index I'm trying to push it to. How can I fix it?
您的问题是,顶层数组中的每个元素都是内存中同一数组的引用,从而导致您遇到的行为。解决此问题的一种方法是使用map
数组方法,以确保用内存中的唯一对象填充顶级数组中的每个元素。
const numberOfSlots = 5;
const numbers = [1, 2, 3, 4, 5, 6, 7, 8]
const nestedArray = Array(numberOfSlots)
.fill(null)
.map(() => new Array());
numbers.forEach((number, index) => {
nestedArray[index % numberOfSlots].push(number)
})
console.log('nested Array', nestedArray)