我对 JS 很陌生,我的一个朋友给我发了这个小提琴
function shortestPath(g, s) {
g.vertexes.forEach(function(u) {
u.dist = Infinity;
u.prev = null;
});
s.dist = 0;
for (var i = 0; i < g.vertexes.length - 1; i++) {
g.edges.forEach(function(e) {
update(e);
});
}
printResult(); }
function update(e) {
var u = e.from;
var v = e.to;
if (v.dist > u.dist + e.data) {
v.dist = u.dist + e.data;
v.prev = u;
} }
var result = [];
function printResult() {
var str = '';
debugger;
for (var i = 0; i < result[0].length; i++) {
for (var j = 0; j < result.length; j++) {
str += result[i][j] + ' ';
}
console.log(str);
str = '';
} }
function printGraph(G) {
var a = [];
G.vertexes.forEach(function(u) {
a.push(u.dist);
});
result.push(a); }
function Graph(options) {
options = options || {};
this.directed = (options.directed != null) ? options.directed : true;
this.vertexes = [];
this.edges = []; }
Graph.prototype.vertex = function(name) {
var v = {
adjacent: [],
name: name.toString()
};
this.vertexes.push(v);
return this; };
Graph.prototype.get = function(name) {
return this.vertexes.filter(function(el) {
return el.name === name.toString();
})[0]; };
Graph.prototype.edge = function(a, b, w) {
var that = this;
connect(a, b, w);
if (!this.directed) {
connect(b, a, w);
}
function connect(a, b, data) {
var u = that.vertexes.filter(function(el) {
return el.name === a.toString();
})[0];
var v = that.vertexes.filter(function(el) {
return el.name === b.toString();
})[0];
u.adjacent.push(v);
that.edges.push({
from: u,
to: v,
data: data
});
}
return this; };
function main() {
var g = new Graph();
g.vertex(1)
.vertex(2)
.vertex(3)
.vertex(4)
.vertex(5)
.vertex(6)
.vertex(7)
.vertex(8);
g.edge(1, 2, -2);
g.edge(1, 5, -2);
g.edge(1, 6, -3);
g.edge(1, 8, -1);
g.edge(2, 6, 7);
g.edge(2, 8, 4);
g.edge(3, 2, 2);
g.edge(3, 4, 5);
g.edge(3, 7, 9);
g.edge(4, 7, 4);
g.edge(5, 7, 5);
g.edge(7, 8, -1);
g.edge(8, 2, 2);
g.edge(8, 5, 8);
g.edge(8, 6, 3);
g.edge(8, 7, 7);
shortestPath(g, g.get(3));
console.log(g); }
main();
(最短路径 Bellman-Ford)并且不明白为什么它会property 'length' of undefined
在控制台中引发错误。
任何建议如何解决此错误?