Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/362.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 关于数组的查询_Javascript_Arrays - Fatal编程技术网

Javascript 关于数组的查询

Javascript 关于数组的查询,javascript,arrays,Javascript,Arrays,我想打印1,2,3,…,9,但上面的代码打印4,5,7,8,9。如果我正确理解了您的问题,您希望控制台记录1到9。按照目前的方式,它只会打印数组中的数组-这就是为什么您只能得到4,5,7,8,9 您可以做的是检查该值是否是第一个循环中的数组-如果是,则对其进行迭代并打印值。如果不是,只需打印值即可 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。

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

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

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]);
这里有一支笔显示结果:

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

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])
}
var printArrayValue=函数(数组){
对于(var i=0;i
这里有一支笔显示结果:

我认为“加入”就足够了:

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);

将每个元素强制为数组:

console.log(arr.join());

这是因为
concat
接受一个数组或单个值。

Kyle Dodge所说的,或者您可以使用下划线/lodash中的
\uu.flatte()
来展平数组。
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]);
}