将数组拆分为N长度的块 [英] Split array into chunks of N length

查看:128
本文介绍了将数组拆分为N长度的块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将数组(包含10个项目)拆分为4个块,其中包含最多 n 项目。

How to split an array (which has 10 items) into 4 chunks, which contain a maximum of n items.

var a = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'];
//a function splits it to four arrays.
console.log(b, c, d, e);

并打印:

['a', 'b', 'c']
['d', 'e', 'f']
['j', 'h', 'i']
['j']

以上假定 n = 3 ,但是,该值应该是动态的。

The above assumes n = 3, however, the value should be dynamic.

谢谢

推荐答案

可能是这样的:

var arrays = [], size = 3;

while (a.length > 0)
    arrays.push(a.splice(0, size));

console.log(arrays);

参见 splice Array的方法。

See splice Array's method.

这篇关于将数组拆分为N长度的块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆