2
我明白我需要改变这个的全局范围,因为在循环中这指的是窗口对象。但如果我尝试通过一个函数来定义我的foreach循环变量它不工作,我不知道为什么,虽然我的函数的返回正确的值:(在foreach循环中调用用户函数
// simple class for xml import
function io() {
this.vertexes = [];
this.getVertexByID = function(id) {
this.vertexes.forEach(function(entry) {
if (id == entry.id) {
// correct element found, displayed and returned
console.log(entry);
return entry;
}
});
}
this.importXML = function(xmlString) {
cells = this.xmlToJson(xmlString);
var parent = graph.getDefaultParent();
var _this = this;
graph.getModel().beginUpdate();
try {
// addEdges
cells.XMLInstance.Edges.Relation.forEach(function(entry) {
// both will be empty but i dont understand why :(
fromVertex = _this.getVertexByID(entry.fromNode);
toVertex = _this.getVertexByID(entry.toNode);
var e1 = graph.insertEdge(parent, null, '', fromVertex, toVertex);
});
} finally {
graph.getModel().endUpdate();
}
}
你错过了最后的'}'。 –
@PatrickBarr编号'el'是用'var'声明的,它的作用范围在函数中。如果它是用'let'声明的话,它会有块级的范围。 var声明的变量作用于其封闭函数或Global,如果不包含在函数中。声明的实际位置并不重要,因为声明已经提出。 –