I am having some trouble with JavaScript scope here, and I don't understand why. My code is as follows:
var objArray = [] //imagine full array
function addDo(){
for(var i = 0; i< objArray.length; i++){
objArray[i].do = function(){
console.log(i);
}
}
}
The problem is that i is always logged as undefined
. How can I make this work? I've had similar problems with async calls, but managed to work around them with closures. Could I do the same here?