Javascript 将阵列拆分为均匀分布的阵列
我试图从1个数组创建4个数组,条件是元素必须均匀分布Javascript 将阵列拆分为均匀分布的阵列,javascript,node.js,arrays,Javascript,Node.js,Arrays,我试图从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
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]
]
这段代码中的错误是什么
-更新
它是这样工作的
const users = [1,2,3,4,5,6];
const userBatch = [[],[],[],[]];
users.forEach((user, index) => {
userBatch[index % 4].push(user);
});
有人能解释一下原因吗?使用并定义数字来创建嵌套数组的数量
const users=[1,2,3,4,5,6];
const userBatch=Array.from({
长度:4
},(v,i)=>[]);
users.forEach((用户,索引)=>{
userBatch[索引%4]。推送(用户);
});
console.log(userBatch)
不要使用。用非原语填充;这样做会在内存中创建一个传递的对象。然后,当您在数组上迭代时,如果在任何索引处对对象进行变异,则每个索引对象都会发生变异,因为所有标记都指向同一个对象。使用Array.from
代替,因为您的填充给出了相同数组的四倍reference@CertainPerformance:尽管重复的方法有助于解释为什么原始方法不起作用,但我认为这个问题同样是关于如何编写起作用的代码。我建议重新打开。@ScottSauyet这个问题确实说明了如何编写有效的代码-只需将.fill
改为数组。from
。不能使用。用非原语填充(在大多数情况下)。@CertainPerformance:我觉得这有问题。但根据我对即将结束的想法,我将把它留在那里。