javascript - 在 foreach 循环中调用用户函数

标签 javascript

我知道我需要更改 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/

相关文章:

javascript - flowplayer隐藏mp3播放器的视频显示

javascript - 如何在类构造函数中记录对象?

javascript - 可滚动对象在Grails 3中不起作用/JavaScript

javascript - 使用 javascript 从 ul li 获取每个层次结构级别的字符串行

javascript - 如何在 javascript/jquery 中将元素追加到现有数组中

javascript - (TS)HTMLInputElement 类型上不存在属性行

javascript - 为什么这个 textarea 看起来只添加了一个空格而不是四个?

javascript - 将 Canvas 时钟设置为系统时间

javascript - jQuery 变量 : Setting variables for the entire file

javascript - 使用 SpiderMonkey 公共(public) API 复制 for...in 循环