提问者:小点点

将数组拆分为平均分布的数组[重复]


我尝试从1个数组创建4个数组,条件是元素必须平均分布。

const users = [1,2,3,4,5,6];
const userBatch = new Array(4).fill([]);
users.forEach((user, index) => {
   userBatch[index % 4].push(user);
});

预期的输出为UserBatch

[
 [1, 5],
 [2, 6],
 [3],
 [4]
]

但它没有发生,则UserBatch的值为

[
  [1, 2, 3, 4, 5, 6]
  [1, 2, 3, 4, 5, 6]
  [1, 2, 3, 4, 5, 6]
  [1, 2, 3, 4, 5, 6]
]

这个代码的错误是什么?


共2个答案

匿名用户

使用array.From并定义数字以创建嵌套数组的数目

null

const users = [1, 2, 3, 4, 5, 6];
const userBatch = Array.from({
  length: 4
}, (v, i) => []);
users.forEach((user, index) => {
  userBatch[index % 4].push(user);
});
console.log(userBatch)

匿名用户

它以这种方法工作

const users = [1,2,3,4,5,6];
const userBatch = [[],[],[],[]];
users.forEach((user, index) => {
   userBatch[index % 4].push(user);
});

有谁能解释一下原因吗?