假设我有一个数组:
var ay=[0,1,2,3,4,5,6,7,8,9];
Run Code Online (Sandbox Code Playgroud)
现在我想得到两个数组:
var ay1=[0,2,4,6,8];
var ay2=[1,3,5,7,9];
Run Code Online (Sandbox Code Playgroud)
有效的方法是什么?
更新:
我知道简单的循环和模运算符方法(如上所述elclanrs),如下所示:
var ay1=[],ay2=[];
for(var i=0,len=ay.length;i++){
if(i%2==0){
ay2.push(ay[i]);
} else
ay1.push(ay[i]);
}
Run Code Online (Sandbox Code Playgroud)
但我只是想知道是否还有其他有效或酷的方式我还不知道.
这就是为什么我问这个简单的问题.我不是问怎么做,我问如果可能的话怎么做得更好!
所以我认为这篇文章不值得投票.
假设我们稍微概括了这个问题.为什么不允许将数组以相同的方式拆分为三个,四个或更多个别数组,而不是仅仅将数组的交替元素拆分为两个数组?
事实证明,允许任意数量的阵列都很容易,因为只做两个.
可以把这个阵列想象成一条由绳子组成的绳子,绳子上有任何数量的绳索,你想解开它.你可以这样做:
// "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] );
Run Code Online (Sandbox Code Playgroud)
这个日志:
[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]
Run Code Online (Sandbox Code Playgroud)
注意,在第二种情况下(count = 3),其中一条链比另外两条长 - 这是预期的,因为10不能被3整除.
| 归档时间: |
|
| 查看次数: |
668 次 |
| 最近记录: |