提问人: 提问时间:12/11/2017 更新时间:12/11/2017 访问量:65
使用 big 回调函数时未定义的数组位置
Undefined Array position when using big callback function
问:
所以,我们的教授要求在 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
答: 暂无答案
评论
console.log
在记录数组之类的东西时撒谎。您在控制台中看到的不是数组的快照,而是数组的“最终”状态 - 调用 heapPermute 时的 var 是什么?ArrayOf Index
bestDistance
bestRoute
distMatrix
debugger;
console.log(JSON.stringify(...))
console.log