2

i have understand that i need to change the global scope of this, because in the loop this refers to the window object. But if i try to define a variable in my foreach loop via a function its not working and i dont know why although my functio returns the correct value :(

// 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();
    }
  }
Mike Cluck
  • 31,869
  • 13
  • 80
  • 91
hansi wasd
  • 97
  • 1
  • 5
  • You are missing the final `}`. – Scott Marcus May 30 '17 at 21:33
  • @PatrickBarr No. `el` is declared with `var` which scopes it to the function. If it were declared with `let` it would have block level scope. `var` declared variables are scoped to their enclosing function or Global if not contained in a function. The actual location of the declaration doesn't matter since declarations are hoisted. – Scott Marcus May 30 '17 at 21:34

1 Answers1

4

Returning a value in a forEach callback has no effect. It certainly is not the return value of the function that the forEach is part of.

So change this:

this.vertexes.forEach(function (entry) {
    if(id==entry.id){
        //correct element found,displayed and returned
        console.log(entry);
        return entry;
    }
});

to this:

return this.vertexes.find(function (entry) {
    return id==entry.id;
});
trincot
  • 317,000
  • 35
  • 244
  • 286