1

Last night, I Googled a lot and couldn't find the solution for my problem: I have a for loop with one function in it which gets me only the latest value from the array.

So, here is the example:

obj1.route = new Routeng();
obj2.route = new Routeng();

for(var x in arrObjs) { //arrObjs = array of objects
  var g = arrObjs[x];

  // I can access properties of all "g" objects

  Routelousse.gen(function(res) {
    var pathern = res.pathern;
    g.routel.staviPather(pathern);

    MYOBJ.vehicles.push(g);
    alert(g.name); // during the loop I always get the LAST "g" object from "arrObjs"
  }, g.point);

}
4
  • Not clear (to me) what you're asking for? Commented Nov 17, 2010 at 10:09
  • @annakata - Because JavaScript doesn't have block scope here, the same g is re-used every for loop pass, so the incorrect one is being used when that asynchronous function completes. Commented Nov 17, 2010 at 10:11
  • @Nick - yeah I understand block scope thanks, what I didn't understand is what the desired result was. But you did it seems so the customer's happy. Commented Nov 17, 2010 at 10:15
  • Are you sure you googled a lot? ;) JavaScript Closures for Dummies(Example 5) is quite helpful... Commented Nov 17, 2010 at 10:16

1 Answer 1

2

It should look like this:

obj1.route = new Routeng();
obj2.route = new Routeng();

for(var x=0; x<arrObjs.length; x++) {
  var g = arrObjs[x];

  (function(ig) {
    Routelousse.gen(function(res) {
      var pathern = res.pathern;
      ig.routel.staviPather(pathern);

      MYOBJ.vehicles.push(ig);
      alert(ig.name);
    }, ig.point);
  })(g);
}

In this we're passing the current g into that self-executing function as a different variable, rather than the g which is shared in the function you're currently in (this isn't block scope) and is changing each pass of the for loop.

Also note the for loop change...you should never use a for...in loop to iterate an Array, use a normal for loop for that.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.