根据奇数/偶数位置将数组拆分为两个数组

2022-01-24 00:00:00 javascript coffeescript

我有一个数组Arr1 = [1,1,2,2,3,8,4,6].

如何根据元素位置的奇数/偶数将其拆分为两个数组?

How can I split it into two arrays based on the odd/even-ness of element positions?

subArr1 = [1,2,3,4]
subArr2 = [1,2,8,6]

推荐答案

你可以试试:

var Arr1 = [1,1,2,2,3,8,4,6],
    Arr2 = [],
    Arr3 = [];

for (var i=0;i<Arr1.length;i++){
    if ((i+2)%2==0) {
        Arr3.push(Arr1[i]);
    }
    else {
        Arr2.push(Arr1[i]);
    }
}

console.log(Arr2);

JS Fiddle 演示.

相关文章