-1

I know WHY this doesn't work, but can't find the correct way of doing it.

I'm trying to build an object using a loop. The Object builds fine, but when I try to use the callback, it alerts "2" for each person, I'd like it to alert the position in the array.

var playerArr = ["steve", "paul", "bob"];

var myAutomatedObj = {};
for (var i=0; i<playerArr.length; i++){
    var objName = playerArr[i];
    myAutomatedObj[objName] = {};
    myAutomatedObj[objName]["callback"] = function(){
        alert(i);
    }
}

//returns incorrect alert
myAutomatedObj.steve.callback();
Richard
  • 1,148
  • 3
  • 18
  • 33

1 Answers1

1

The property i is referenced by each function, because it's in their scope, but its value equals the length of the array at the end of the loop.

Try the following:

myAutomatedObj[objName]["callback"] = (function(j) {
    return function(){
        alert(j);
    }
})(i);

This way you actually copy the value and you are no longer referencing the variable named i.

skypjack
  • 49,335
  • 19
  • 95
  • 187
  • Can't thank you enough - I knew what was happening, but not how to stop it - I'll accept this answer when it allows me to (10 minutes). – Richard Jan 17 '16 at 00:15