【发布时间】:2020-04-20 16:05:15
【问题描述】:
我有一个原始数组,一个简单的列表(“内容”)。我想遍历它并将内容输出到容器数组内的一系列新数组中,每个新数组对应一个系列的增量,具有给定的限制。
这将是起源: var content = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I']
我尝试了各种方法。这是我的最新版本:
let buildAndFill = function (content, n) {
let container = [];
let innerArrayCounter = 0;
for (i = 0; i < n; i++) {
// for each iteration up to n, create inner arrays and push them to container
container.push([]);
// traverse 'content', and get the item at a given index and push to an inner array in 'container'
content.forEach(function (item, index, object) {
// Set the inner array counter to a number between zero and n, accoring to its index position in content
innerArrayCounter = (index%n);
// push the value of index into the inner array
container[innerArrayCounter].push(item);
});
};
return container;
};
// 这条线破坏了程序。内部数组未定义: 容器[innerArrayCounter].push(item);
这是我用来检查每一行的 console.log() 测试的函数:
let buildAndFill = function (content, n) {
let container = [];
let innerArrayCounter = 0;
for (i = 0; i < n; i++) {
container.push([]);
// add some content to the newly created inner arrays
container[i].push('inner content');
// test for the content of the container
console.log(container);
content.forEach(function (item, index, object) {
// test is I can access content: log the current item
console.log(content[index]);
// test if I can access 'container' from inside this function
console.log(container[i]);
// Set the inner array counter to a number between zero and n, accorind to its index position in content
if (index <= n) innerArrayCounter = index;
else innerArrayCounter = (index%n);
// test: log the current inner array counter
console.log(' the value of the counter is ' + innerArrayCounter);
// test: log the current index
console.log('the current index is ' + index);
// test if I can access the inner array of container by using the countner as the array index
console.log('the contents of the inner array is ' + container[innerArrayCounter]);
// push the value of index into the inner array
container[innerArrayCounter].push(item);
// ^THIS LINE BREAKS THE PRORGAM. INNER ARRAY BECOMES UNDEFINED:
// test: log the contents of the array
console.log('after push the contents of the inner array is ' + container[innerArrayCounter]);
});
};
return container;
};
想要的结果
buildAndFill(内容, 3);
应该是:
[['A','D','G'],['B','E','H'],['C','F','I']]
【问题讨论】:
-
tbh,我不明白你想要什么,但请尝试将
let container = [];更改为let container = Array(n).fill([])并删除container.push([]);。 -
谢谢。我编辑了问题以添加所需的结果。是不是更清楚了?
-
谢谢。我尝试过这个。它修复了 undefined 的问题,此更改允许整个函数执行正常。 TY 的建议。
标签: javascript arrays