我知道我需要更改 this 的全局范围,因为在循环中 this 引用了窗口对象。但是,如果我尝试通过函数在 foreach 循环中定义变量,它不起作用,我不知道为什么,尽管我的 functio 返回了正确的值:(
// 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();
}
}
最佳答案
在 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;
});
关于javascript - 在 foreach 循环中调用用户函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44272189/