繁体   English   中英

将数组中的块推入JavaScript中的另一个数组

[英]Push chunks of an array into another array in JavaScript

我有一个包含速度的映射点数组,我想创建一个每25个点的新数组并将其推入另一个称为块的数组中。 所以这就是我在做什么:

var chunks = []; // the array of chunks
var tempArray = []; //used for storing current chunk
var currentLoop = 0; //used for checking how many items have been taken
for (var i = 0; i < gon.map_points.length; i++) {
    if (currentLoop == 26) { // if the current items stored is above 25
        chunks.push(tempArray); // push the chunk
        currentLoop = 0; // reset the count
        tempArray = []; // reset the chunk
    }
    tempArray.push(gon.map_points[i].speed); // add item into chunk
    currentLoop++; // increase count
}

因此,除非映射点的数组不是完美的点数(例如,可能是117个),否则此方法效果很好,因此,我不会将最后的17个点添加到块数组中。

有没有一种方法可以将数组分成25个点,而不管总项目数是多少?

您可以使用Array#slice和一个索引,然后根据需要增加大小。

 var array = Array.apply(null, { length: 65 }).map(function (_, j) { return j; }), chunks = [], chunkSize = 25, i = 0; while (i < array.length) { chunks.push(array.slice(i, i + chunkSize)); i += chunkSize; } console.log(chunks); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

您可以使用拼接来设置像这样的块

 var s = []; var result = []; function generate(){ for(var i=0 ; i< 117; i++){ s.push(i); } } generate(); //console.log(s) while(s.length > 25){ //console.log(s.splice(0,25)) result[result.length] = s.splice(0,25); } result[result.length] = s; console.log(result); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM