将数组拆分为块 [英] Split array into chunks

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

问题描述

假设我有一个如下所示的 Javascript 数组:

Let's say that I have an Javascript array looking as following:

["Element 1","Element 2","Element 3",...]; // with close to a hundred elements.

什么方法适合将数组分块(拆分)为许多更小的数组,比如最多 10 个元素?

What approach would be appropriate to chunk (split) the array into many smaller arrays with, lets say, 10 elements at its most?

推荐答案

array.slice 方法可以根据需要从数组的开头、中间或结尾提取切片,而无需更改原始数组.

The array.slice method can extract a slice from the beginning, middle, or end of an array for whatever purposes you require, without changing the original array.

var i,j, temporary, chunk = 10;
for (i = 0,j = array.length; i < j; i += chunk) {
    temporary = array.slice(i, i + chunk);
    // do whatever
}

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

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