简体   繁体   English

没有固定大小的JS多维数组

[英]JS Multidimensional Array with No Fixed Size

In my program I have: 在我的程序中,我有:

an array currentIndex that will look something like [1, 2, 2] a multidimensional array directions that looks like [1, [2, 0, [2, 3, -]] 1] 数组currentIndex看起来像[1,2,2],多维数组方向看起来像[1,[2,0,[2,3,-]] 1]

How can I loop through the first one in such a way that I can access directions[1][2][2] (turn the first array in the indexes of the second) ? 如何以一种可以访问directions [1] [2] [2](将第一个数组作为第二个数组的索引)的方式遍历第一个?

To access directly one value you could use vector[1][2] , but remember that the array index starts with 0 . 要直接访问一个值,可以使用vector[1][2] ,但请记住,数组索引以0开头

But, if you want to walk through the vector you need a recursive function: 但是,如果要遍历向量,则需要递归函数:

function printRecursiveArray(value, c){
  for(c=0; c<value.length; c++){

    if (typeof value[c] !=='object'){
      console.log(value[c]);     
    }else{
      printRecursiveArray(value[c],0);

    }

  }
}
var vector = [1,[1,2,3],2,3];
printRecursiveArray(vector,0);
console.log('vector[1][2]:' + vector[1][2]);// To access directly

So, your array could have any dimension, but you still print the elements. 因此,您的数组可以具有任何尺寸,但是您仍然可以打印元素。

From what I understand you want to iterate through the first array where each value in the first array is the index you want to access in the multidimensional array. 据我了解,您想遍历第一个数组,其中第一个数组中的每个值都是要在多维数组中访问的索引。 The following recursive function should work: 以下递归函数应该起作用:

//index: Array of indexes 
//arr: The mutlidimensional array 
function accessMutliArr (index, arr) {
    if (index.length === 1)
        return arr [ index ];
    else {
        var currentIndex = index.splice(0, 1);
        return accessMutliArr (index , arr [ currentIndex ]);
    }
}

If you want to loop over a multidimensional Array then the process can look like: 如果要遍历多维数组,则过程可能如下所示:

for(var i in directions){
  for(var n in direction[i]){
    for(var q in directions[i][n]){
      var innerIncrement = q, innerValue = directions[i][n][q];
    }
  }
}

Take into account that a for in loop will automatically make your indexes Strings. 考虑到for in循环将自动使您的索引字符串。 The following is a fail proof way to do the same thing, with some other help: 以下是在做其他事情时可以做同样的事情的一种失败证明方法:

for(var i=0,l=directions.length; i<l; i++){
  var d = directions[i];
  for(var n=0,c=d.length; n<c; n++){
    var d1 = d[n];
    for(var q=0,p=d1.length; q<p; q++){
      var innerIncrement = q, innerValue = d1[q];
    }
  }
}

When you do a loop like either of the above, imagine that each inner loop runs full circle, before the outer loop increases its increment, then it runs full circle again. 当您执行上述任一循环时,请想象每个内部循环运行一个完整的圆,然后再外部循环增加其增量,然后再次运行整个完整的圆。 You really have to know what your goal is to implement these loops. 您确实必须知道实现这些循环的目标。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM