I get an " Uncaught TypeError: Cannot read property 'length' of undefined " at line 26. I can't see the reason this is happening, because the console logs line 24 as an array with a value at index 1, but line 25 logs as undefined.
"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));
}
Output:
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
1 Answer 1
EDIT - per your comments, it looks like you have an array of arrays, and that, if I understand you correctly, M[i[1]] should be M[i][1]
You're checking
console.log(M[i[0]]);
but then accessing
var last = M[i[1]].length;
it seems as though M[i[0]] contains a valid array, but M[i[1]] does not.
I would recommend taking a closer look at your M, and i arrays to figure out why M[i[1]] is undefined.
Edit, as the comment below says, i appears to be the loop control variable. Did you mean to type simply M[i] ?
7 Comments
i is the loop counter not an arrayconsole.log(M[i]); returns the contents as 0 in the 0 index, and an array in the 1 index, but both M[i[0]] and M[i[0]] come back as undefined.i is an integer, then M[i[0]] is simply invalid. What are you trying to do?
M[i[0]]andM[i[1[last]]]?