如何将一个数组拆分成相等大小的数组:
var a = [1,2,3,4,5,6,7,8];
var b = a.split(2);
// b is equal to [[1,2],[3,4],[5,6],[7,8]];
// one possible way might be something like
[0,1,2,3].map(_ => a.slice(_* 2, _+2));
答案 0 :(得分:0)
const chunk = (arr, size) => arr.reduce((carry, _, index, orig) => !(index % size) ? carry.concat([orig.slice(index,index+size)]) : carry, []);
console.log(chunk([1,2,3,4,5,6,7,8], 2))
答案 1 :(得分:0)
对于第二个要拼接的索引,您需要加一个并乘以内部数组的长度。
var a = [1, 2, 3, 4, 5, 6, 7, 8],
b = [0, 1, 2, 3].map(i => a.slice(i * 2, (i + 1) * 2));
console.log(b);