有关数组的查询

Query regarding arrays

本文关键字:查询 数组      更新时间:2023-09-26
var arr=[1,2,3,[4,5],6,[7,8,9]],x,j;
for(x in arr)
   for(j in arr[x])
       console.log(arr[x][j]);

我想打印 1,2,3,...,9,但上面的代码打印 4,5,7,8,9。

我认为"加入"就足够了:

console.log(arr.join());

如果我正确理解您的问题,您希望控制台记录 1 到 9。你目前拥有它的方式,它只会打印你的数组中的数组 - 这就是为什么你只得到 4,5,7,8,9。

您可以做的是检查该值是否是第一个循环中的数组 - 如果是,则迭代它并打印值。如果不是,只需打印值。

if(arr[x].constructor === Array) {
    //loop over the array and print out the values
    for (j in arr[x]) {
      console.log(arr[x][j])
    }
} else {
    //print out the plain value
    console.log(arr[x])
}

这是一支笔来显示结果:http://codepen.io/kyledodge/pen/zGwPBo

另一种选择是使用递归。你可以做这样的事情:

var printArrayValue = function(array) {
  for (var i = 0; i < array.length; i++) {
    if (array[i].constructor === Array) {
      //if this an array, call this function again with the value
      printArrayValue(array[i]);
    } else {
      //print the value
      console.log(array[i]);
    }
  }
}
printArrayValue(arr);

这是一支笔来显示结果:http://codepen.io/kyledodge/pen/VLbrPX

强制每个元素到数组:

var arr=[1,2,3,[4,5],6,[7,8,9]],x,j;
for(x in arr) {
    var arr2 = [].concat(arr[x]);
               ^^^^^^^^^^^^^^^^^
    for(j in arr2)
       console.log(arr2[j]);
}

这是有效的,因为concat采用数组或单个值。