2012-12-08 56 views
1

我得到一个“Uncaught TypeError:无法读取属性的'未定义的长度'在第26行。我看不到这种情况发生的原因,因为控制台将第24行记录为一个值为索引1,但第25行记录为未定义。未定义的数组元素

"use strict" 
function findpath(G,si,di){ 
    //G is an array of nodes (with id, lat, lon) 
    var P=[si]; 
    var C=[0,P]; 
    var M=[C]; 
    var O=[]; 
    var ctr=0; 
    var done = false; 
    var reached = false; 
    var best = undefined; 


    while(!done){ 
     ctr++; 
     if(ctr > 100){ 
      alert("Sorry, can't find the destination."); 
      return P; 
     } 

     for (var i=0;i<M.length;++i){ 
      console.log(P); 
      console.log(C); 
      console.log(M[i]); 
      console.log(M[i[0]]); 
      var last = M[i[1]].length; 
      var v = M[i[1[last]]]; 

      //select a random neighbor... 
      if(v.N.length === 0){ 
       alert("Wat?"); 
       return []; 
      } 
      else if(v.N.length === 1){ 
       break; 
      } 
      else if(v === di){ 
       break; 
      } 
      else { 
       for (var j=0;j<v.N.length;++j){ 
        var temp = M[i]; 
        O.push(temp[1].push(v.N[j])); 
        var dist = distance(v.lat,v.lon,v.N[j].lat,v.N[j].lon); 
        var temp2 = O.length-1; 
        O[temp2[0]]+=dist; 
        if (v.N[j]===di){ 
         reached = true; 
         if (best === undefined){ 
          console.log("ASSIGN"); 
          best = O[temp2]; 
         } 
         else { 
          if (O[temp2[0]]<best[0]) { 
           best = O[temp2]; 
          } 
         } 
        } 
       } 
      } 
     } 
     M = O; 
     var any = false; 
     for (var i=0;i<M.length;++i) { 
      if (M[i[0]]<best[0]) { 
       any = true; 
      } 
     } 
     if (!any) { 
      done = true; 
     } 
    } 

    //return the path 
    return best[1]; 
} 

function distance(x1,y1,x2,y2){ 
    return Math.sqrt(Math.pow((x2-x1),2)+Math.pow((y2-y1),2)); 
} 

输出:

Array[1]  findpath.js:22 
Array[2]  findpath.js:23 
Array[2] 
    0: 0 
    1: Array[1] 
     0: 13 
    length: 1 
    __proto__: Array[0] 
    length: 2 
    __proto__: Array[0]  findpath.js:24 
undefined findpath.js:25 
Uncaught TypeError: Cannot read property 'length' of undefined findpath.js:26 
+0

你想用'M [i [0]]'和'M [i [1 [last]]'来做什么? – Musa

回答

3

编辑 - 根据您的意见,它看起来就像你有一个数组的数组,并说,如果我理解正确的话,M[i[1]]应该M[i][1]


您正在检查

console.log(M[i[0]]); 

但随后访问

var last = M[i[1]].length; 

它好像M[i[0]]包含一个有效的数组,但M[i[1]]没有。

我建议仔细看看您的Mi阵列,找出为什么M[i[1]]未定义。


编辑,如下面的评论所述,i似乎是循环控制变量。你的意思是简单地输入M[i]

+0

'i'是循环计数器不是数组 – Musa

+0

问题是'console.log(M [i]);'在0索引中返回内容为'0',而在1索引中返回一个数组,但两者都返回'M [i [0]]'和'M [i [0]]'回到未定义状态。 – iwhitt567

+0

@ iwhitt567 - 如果'i'是一个整数,那么'M [i [0]]'就是无效的。你想做什么? –