合并2个函数以防止最大调用堆栈大小超出错误

时间:2017-06-10 17:00:27

标签: javascript arrays matrix multidimensional-array

我想将2个函数组合在一起,以防止最大调用堆栈大小超出错误。我在stackoverflow上读到了这个错误并看到了示例,但我仍然无法完成并实现解决方案。有人可以帮帮我吗?

var array = new Array(3);
for (var i = 0; i < array.length; i++) {
   array[i] = new Array(3);
}
//for example array has 3 rows and 3 columns. Function compute a determinant of the array

function compute(){
   var i, j;
   var array1 = array.slice();

   for (i = 0; i < array1.length; i++) {
      for (j = 0; j < array1[i].length; j++) {
         array1[i][j] = parseInt(document.getElementById("element"  + (i+1) + (j+1)).value, 10);
      }
   }
   document.getElementById("result").innerHTML = det(array1);
}
function det(array1){
   var i, j, k;
   var result = 0;

   if(array1.length == 1) return array1[0][0];

   for(i = 0;i < array1[0].length;i++){
      var z = 1;
      if(i%2 != 0) z = -1;
      var multiplier = array1[0][i];
      var m = new Array();
      var m2 = new Array();

      for(j = 1;j < array1.length; j++){
         var l = 0;
         for(k = 0;k < array1[j].length - 1; k++){
            if(k==i) l = 1;
            m2[k] = array1[j][k+l];
         }
         m[j-1]= m2;
         m2 = new Array();
      }
      result += z * multiplier * det(m);
   }
return result;
}

0 个答案:

没有答案