Javascript:将数组拆分为多个部分

时间:2017-05-04 10:40:40

标签: javascript arrays

我有一个可以任意长度的数组。并需要将其分成几个部分。第一部分的长度为14,长度为16之后

var size1 = 14;
var size2 = 16;
var a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21,
        22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40];
var arrays = [];
if (a.length > 14){
    for (i = 0; i < 14; i++) {
        arrays.push(a.splice(0, size1));
    } 
    for (i = 14 ; i < a.length; i++){
        arrays.push(a.splice(0, size2));

    }
} else {
    arrays.push(a.splice(0, size1));

}
console.log(arrays);

然而,基于我正在做的事情,我的阵列只能在14处分裂。你能就我如何做到这一点提出建议吗?

谢谢

3 个答案:

答案 0 :(得分:1)

使用Array.prototype.slice()函数的解决方案:

&#13;
&#13;
var a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21,
    22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40],
    size1 = 14,
    size2 = 16,
    arrays = [];

[0, size1, size2].forEach(function (v, i, arr) {
    arrays.push((arr[i+1])? a.slice(v, v + arr[i+1]) : a.slice(arr[i-1] + v));
});

console.log(arrays);
&#13;
&#13;
&#13;

答案 1 :(得分:1)

您可以使用数组作为块长度,其余部分使用零,并通过保留前面长度的长度来映射块。

适用于任意数量的块。

&#13;
&#13;
var chunks = [14, 16, 0],
    array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40],
    result = chunks.map((last => a => array.slice(last, a ? (last += a) : undefined))(0));

console.log(result);
&#13;
.as-console-wrapper { max-height: 100% !important; top: 0; }
&#13;
&#13;
&#13;

答案 2 :(得分:0)

你可以尝试使用所有动态数组大小,它会得到你想要的输出。 希望您正在寻找这个解决方案。

var size1 = 14;
var size2 = 16;
var flag=0;
var a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21,
                22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40];
var arrays = [];
var t=a.length/14;
while(a.length>0){
        if (flag==0 && a.length > 14){
                arrays.push(a.splice(0, size1));
                flag=1;
        } else if(a.length>=16){
            arrays.push(a.splice(0, size2));
        }
        else{
            arrays.push(a.splice(0, a.length));
        }
}
        console.log(arrays)