如何使用嵌套循环JS创建一个新的数组形式嵌套数组

时间:2017-11-30 04:51:19

标签: javascript arrays for-loop nested-loops

我有一个嵌套数组,我需要创建两个新数组,一个用于偶数,另一个用于奇数,使用嵌套for循环。 我使用了push方法,但结果是每个数字都在一个单独的数组中,而我需要在一个数组中设置所有偶数,而对于奇数数字则相同。

这是我的代码:

var numbers = [
  [243, 12, 23, 12, 45, 45, 78, 66, 223, 3],
  [34, 2, 1, 553, 23, 4, 66, 23, 4, 55],
  [67, 56, 45, 553, 44, 55, 5, 428, 452, 3],
  [12, 31, 55, 445, 79, 44, 674, 224, 4, 21],
  [4, 2, 3, 52, 13, 51, 44, 1, 67, 5],
  [5, 65, 4, 5, 5, 6, 5, 43, 23, 4424],
  [74, 532, 6, 7, 35, 17, 89, 43, 43, 66],
  [53, 6, 89, 10, 23, 52, 111, 44, 109, 80],
  [67, 6, 53, 537, 2, 168, 16, 2, 1, 8],
  [76, 7, 9, 6, 3, 73, 77, 100, 56, 100]
];

for (var x = 0; x < numbers.length; x++) {
    for (var y = 0; y < numbers[x].length; y++) {
    if (numbers[x][y] % 2 === 0) {
        var even = [];
        even.push(numbers[x][y]);
    } else {
        var odd = [];
        odd.push(numbers[x][y]);
    }
    console.log(odd);
}

3 个答案:

答案 0 :(得分:0)

var odd = [], even= [];
for (var x = 0; x < numbers.length; x++) {
    for (var y = 0; y < numbers[x].length; y++) {
    if (numbers[x][y] % 2 === 0) {
        even.push(numbers[x][y]);
    } else {
        odd.push(numbers[x][y]);
    }
    console.log(odd);
}

将偶数和奇数变量放在循环之外

答案 1 :(得分:0)

您必须将所有嵌套数组合并到一个新数组中,然后您可以分别找到所有奇数和偶数数字

&#13;
&#13;
var numbers = [
  [243, 12, 23, 12, 45, 45, 78, 66, 223, 3],
  [34, 2, 1, 553, 23, 4, 66, 23, 4, 55],
  [67, 56, 45, 553, 44, 55, 5, 428, 452, 3],
  [12, 31, 55, 445, 79, 44, 674, 224, 4, 21],
  [4, 2, 3, 52, 13, 51, 44, 1, 67, 5],
  [5, 65, 4, 5, 5, 6, 5, 43, 23, 4424],
  [74, 532, 6, 7, 35, 17, 89, 43, 43, 66],
  [53, 6, 89, 10, 23, 52, 111, 44, 109, 80],
  [67, 6, 53, 537, 2, 168, 16, 2, 1, 8],
  [76, 7, 9, 6, 3, 73, 77, 100, 56, 100]
];
var merged = [].concat.apply([], numbers);
var evenValues = [];
var oddValues = [];
for (var i = 0; i < merged.length; i++) {
  if ((merged[i] % 2) != 1) {
    evenValues.push(merged[i]);
  } else {
    oddValues.push(merged[i]);
  }
}
console.log(evenValues);
console.log(oddValues);
&#13;
&#13;
&#13;

答案 2 :(得分:-1)

编写var even = [];var even = new Array();的快捷方式,因此,当您在循环中执行此操作时,您将在每次迭代时创建一个新数组,并且每个新数组都会覆盖前一个数组。例如,以下代码创建3个不同的数组并仅保存最后一个(在i = 2时定义):

for (var i = 0; i < 3; i++) {
  var a = [i];
}
console.log(a); // [2]

如果整个循环只需要一个数组,则必须在循环外定义它:

var a = [];
for (var i = 0; i < 3; i++) {
  a.push(i);
}
console.log(a); // [0, 1, 2]