我试图将我的 9 个元素数组拆分为 3 个数组,每个数组包含 3 个元素。
const data = [{
name: 'a',
surname: 'b'
},
{
name: 'a',
surname: 'b'
},
{
name: 'a',
surname: 'b'
},
{
name: 'a',
surname: 'b'
},
{
name: 'a',
surname: 'b'
},
{
name: 'a',
surname: 'b'
},
{
name: 'a',
surname: 'b'
},
{
name: 'a',
surname: 'b'
},
{
name: 'a',
surname: 'b'
},
];
const chunks = Array(3).fill(Array());
data.forEach((value, index) => chunks[index % chunks.length].push(value));
console.log(chunks);
我不明白为什么它会生成 3 个数组,每个数组中有 9 个元素。
chunks[index%chunks.length].push(value)
有什么问题?
最佳答案
发生这种情况是因为 fill
向每个元素返回相同的数组,因此推送到这三个元素中的任何一个实际上就是推送到相同的引用。
在 MDN 文档中提到:
The fill() method fills (modifies) all the elements of an array from a start index (default zero) to an end index (default array length) with a static value. It returns the modified array.
^-- STATIC 值。 Read more about fill here
为了更清楚,这个:
const chunks = Array(3).fill(Array());
可以这样“解释”:
const chunks = new Array(3);
var arr = new Array();
for (var i = 0; i < chunks.length; i++) chunks.push(arr);
所以,基本上,数组的相同引用被推送到原始数组;因此,改变 arr
意味着改变它的所有引用,所以 chunks
中的所有引用都指向同一个数组,所以都被“改变”了,这意味着它们都将指向相同的数组并共享相同的值。
您可以通过多种方式解决这个问题,我能想到的最快的方法是使用 Array.from
,如下所示,回调每次都会返回一个新数组。
const data = [
{
name: 'a',
surname: 'b'
},
{
name: 'a',
surname: 'b'
},
{
name: 'a',
surname: 'b'
},
{
name: 'a',
surname: 'b'
},
{
name: 'a',
surname: 'b'
},
{
name: 'a',
surname: 'b'
},
{
name: 'a',
surname: 'b'
},
{
name: 'a',
surname: 'b'
},
{
name: 'a',
surname: 'b'
},
];
const chunks = Array.from({length: 3}, (_) => []);
data.forEach((value, index) => chunks[index%chunks.length].push(value));
console.log(chunks);
相关代码解释
Array.from({length: 3}, (_) => []);
- Array.from 从定义的属性列表中创建一个新数组。在本例中,它创建了一个长度为 3 的新数组。
(_) => []
是为数组的每个元素分配值而调用的回调。在这种情况下,我只是返回一个新 数组。这也可以缩短为:() => []
就是这样。
关于javascript - 如何将对象数组拆分为 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57356613/