我已经明白我需要改变它的全局范围,因为在循环中这指的是窗口对象。但是,如果我尝试通过一个函数在我的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();
}
}
答案 0 :(得分:4)
在forEach
回调中返回值无效。它当然不是forEach
所属函数的返回值。
所以改变这个:
this.vertexes.forEach(function (entry) {
if(id==entry.id){
//correct element found,displayed and returned
console.log(entry);
return entry;
}
});
到此:
return this.vertexes.find(function (entry) {
return id==entry.id;
});