[英]Pushing every value from an Array to multiple sub-arrays
i would like given an array in javascript and a number variable to create new arrays from the number and then push every member of the "big" array to the sub-arrays. 我想在javascript和数字变量中给定一个数组,以便从该数字创建新数组,然后将“大”数组的每个成员推送到子数组。 The first value from the array goes to the 1st sub-array the second goes to the 2nd sub-array, the 3rd to 3rd etc.Here is how i do it with 2 arrays:
来自数组的第一个值进入第一个子数组,第二个进入第二个子数组,第3到第3等等,这是我如何使用2个数组的方法:
r1=new Array();
r2=new Array();
for(var i=0; i<array.length; i++){
if(i%2 == 0){
r1.push(array[i]);
}
else
{
r2.push(array[i]);
}
}
Suppose we have a number variable that is meaning to be the sub arrays , we would then have to do 假设我们有一个数字变量,意味着它是子数组,那么我们将不得不做
for(var j=0;j<number;j++){
r[j]=[];
}
What is the best solution for this?Maybe array.map could help?Thanks. 最好的解决方案是什么?也许array.map可以帮助您?
Here's a general purpose solution for splitting among N arrays. 这是在N个阵列之间分割的通用解决方案。 It returns an array of the resulting arrays.
它返回结果数组的一个数组。
function splitArray(src, num) {
var result = [], i;
// initalize output arrays
for (i = 0; i < num; i++) {
result.push([]);
}
// split results among the various output arrays
for (i = 0; i < src.length; i++) {
result[i % num].push(src[i]);
}
return(result);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.