使用 big 回调函数时未定义的数组位置

Undefined Array position when using big callback function

提问人: 提问时间:12/11/2017 更新时间:12/11/2017 访问量:65

问:

所以,我们的教授要求在 JavaScript 中制作一个蛮力旅行推销员,这是我正在使用的排列算法:

function heapPermute(A, callback){
  var n = A.length;
  var c = [];
  var i = 0;

  for(i = 0; i < n; i++){
    c[i] = 0;
  }

  callback(A);

  i = 0;
  while(i < n){
    if(c[i] < i){
      if(i % 2){
        swap(A, c[i], i);
      }else{
        swap(A, 0, i);
      }
      callback(A);
      c[i]++;
      i = 0;
    }else{
      c[i] = 0;
      i++;
    }
  }
}

并按如下方式调用它:

heapPermute(ArrayOfIndex, function(input){
    console.log(input);
});

ArrayOfIndex = [1,2,3] 的控制台输出

Array [ 0, 1, 2 ]
Array [ 1, 0, 2 ]
Array [ 2, 0, 1 ]
Array [ 0, 2, 1 ]
Array [ 1, 2, 0 ]
Array [ 2, 1, 0 ]

问题是,当我使用像 console.log()这样的简单回调函数时,代码运行没有问题,并且控制台记录所有排列,但是如果我尝试使用索引来计算最佳路由,则在访问数组位置时会得到 Undefined。

bestDistance = Number.MAX_SAFE_INTEGER;
distMatrix = //Matrix read from .json;
bestRoute = [];

function checkIfBestRoute(route){

  console.log(route);   //this prints an Array with 2 undefined positions


  //distMatrix is global
  var distance = distMatrix[route[route.length - 1]][route[0]];    //Undefined route[0]

  for(var i = 0; i < route.length - 1; i++){
    distance += distMatrix[route[i]][route[i + 1]];
  }

  if(distance < bestDistance){
    bestDistance = distance;
    bestRoute = route.splice(0);
  }
}

heapPermute(ArrayOfIndex, checkIfBestRoute);    //Undefined route[0] trace

调用函数时的控制台输出,如上面的块,ArrayOfIndex = [0, 1, 2, 3]

Array [ 0, 1, 2, 3 ]
Array [ undefined, undefined ]
TypeError: route[0] is undefined
javascript 未定义 undefined-index

评论

0赞 Jaromanda X 12/11/2017
console.log在记录数组之类的东西时撒谎。您在控制台中看到的不是数组的快照,而是数组的“最终”状态 - 调用 heapPermute 时的 var 是什么?ArrayOf Index
0赞 12/11/2017
它是一个数组,包含用户选择的所有索引来创建路由,
0赞 Jaromanda X 12/11/2017
那么,一个数字数组?你有一些像 AND 这样的全局变量,但你也没有展示,所以,很难告诉你你做错了什么bestDistancebestRoutedistMatrix
0赞 12/11/2017
上次区块已编辑
1赞 Amadan 12/11/2017
为了省去麻烦,要么使用断点(或语句)在要检查代码的位置停止代码,要么使用断点来保持诚实。debugger;console.log(JSON.stringify(...))console.log

答: 暂无答案