gpt4 book ai didi

javascript - 数组元素不拼接成单独的数组 - FreeCodeCamp > Chunky Monkey

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:18:25 30 4
gpt4 key购买 nike

我正在应对 FreeCodeCamp 挑战,但遇到了以下挑战:

Our goal for this Algorithm is to split arr (first argument) into smaller chunks of arrays with the length provided by size (second argument). There are several green checks (objectives) our code needs to pass in order to complete this Algorithm:

(['a', 'b', 'c', 'd'], 2) is expected to return [['a', 'b'], ['c', 'd']]

([0, 1, 2, 3, 4, 5], 3) is expected to return [[0, 1, 2], [3, 4, 5]]

([0, 1, 2, 3, 4, 5], 2) is expected to return [[0, 1], [2, 3], [4, 5]]

([0, 1, 2, 3, 4, 5], 4) is expected to return [[0, 1, 2, 3], [4, 5]]

([0, 1, 2, 3, 4, 5, 6, 7, 8], 2) is expected to return [[0, 1], [2, 3], [4, 5], [6, 7], [8]].

这是我想出的代码:

function chunkArrayInGroups(arr, size) {

var newArray = [];
var holdArray = [];
for (var i = 0; i <= arr.length; i += size) {
holdArray = arr.slice(0, size);
removed = arr.splice(0, size);
newArray.push(holdArray);
}
if (arr.length !== 0) {
newArray.push(arr);
return newArray;
}
else return newArray;
}

chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 2);

该算法适用于除最后一个目标之外的所有目标。而不是返回:

[[0, 1], [2, 3], [4, 5], [6, 7], [8]]

它正在返回:

[[0, 1], [2, 3], [4, 5], [6, 7, 8]] - 我不知道为什么。

如果能帮助我弄清楚哪里出了问题,我们将不胜感激!

最佳答案

我不怪你一头雾水,我也花了一段时间才找到问题。

首先确定您的 for 循环有点奇怪 - 您没有将 i 变量用于任何事情。此外,您 splice() 每次迭代都将原始数组向下,因此您的意图是正确的 - 等待直到数组中剩余的元素少于 size

所以我将其表示为 while 循环,瞧,它有效:

function chunkArrayInGroups(arr, size) {

var newArray = [];
var holdArray = [];
while (arr.length >= size) {
holdArray = arr.slice(0, size);
removed = arr.splice(0, size);
newArray.push(holdArray);
}
if (arr.length !== 0) {
newArray.push(arr);
return newArray;
}
else return newArray;
}

chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 2);

关于javascript - 数组元素不拼接成单独的数组 - FreeCodeCamp > Chunky Monkey,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40208349/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com