假设我们将这个问题概括一下。与其将数组的交替元素拆分为两个数组,为什么不允许以相同的方式将数组拆分为三个、四个或更多单独的数组?
事实证明,允许任意数量的数组与只允许两个数组一样容易。
将阵列想象成一根由股线组成的绳索,无论绳索中有多少股线,您都想解开它。你可以这样做:
// "Unravel" an array as if it were a rope made up of strands, going
// around the rope and pulling off part of each strand one by one.
// 'rope' is the array and 'count' is the number of strands.
// Return an array of arrays, where the outer array has length 'count'
// and the inner arrays represent the individual strands.
function unravel( rope, count ) {
// Create each strand
var strands = [];
for( var i = 0; i < count; i++ ) {
strands.push( [] );
}
// Unravel the rope into the individual strands
for( var i = 0, n = rope.length; i < n; i++ ) {
strands[ i % count ].push( rope[i] );
}
return strands;
}
var rope = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ];
var s = unravel( rope, 2 );
console.log( s[0], s[1] );
var s = unravel( rope, 3 );
console.log( s[0], s[1], s[2] );
var s = unravel( rope, 5 );
console.log( s[0], s[1], s[2], s[3], s[4] );
这记录:
[0, 2, 4, 6, 8] [1, 3, 5, 7, 9]
[0, 3, 6, 9] [1, 4, 7] [2, 5, 8]
[0, 5] [1, 6] [2, 7] [3, 8] [4, 9]
请注意,在第二种情况下(count=3),其中一条链比其他两条长——这是可以预料的,因为 10 不能被 3 整除。