在 JavaScript 中根据 N 计数按部分拆分数组

javascriptweb developmentfront end technologyobject oriented programming更新于 2026/1/19 2:52:17

我们需要编写一个 JavaScript 函数,该函数接受一个文字数组和一个数字(例如 n)。

该函数应返回一个新数组,该数组被分成 n 个子数组,假设 n 始终小于或等于数组的长度。

例如:如果输入数组是 −

const arr = [1,2,3,4,5,6,7,8,9,10];
const n = 3;

那么输出应该是 −

const output = [[1,2,3],[4,5,6],[7,8,9,10]];

示例

其代码为 −

const arr = [1,2,3,4,5,6,7,8,9,10];
const n = 3;
const divideIntoChunks = (arr, count) => {
   const res = [];
   const size = arr.length / count;
   let ind = 0;
   while (ind < arr.length) {
      res.push(arr.slice(ind, ind += size));
   };
   return res;
};
console.log(divideIntoChunks(arr, n));

输出

控制台中的输出 −

[ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9, 10 ] ]

相关文章


有用资源