0

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?

Jo Colina
  • 1,870
  • 7
  • 28
  • 46
  • It can't log `undefined` with your code. unless you set `i = undefined` after for loop. – dfsq Jul 03 '15 at 10:27
  • Read this for JavaScript Scope: http://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript – SK. Jul 03 '15 at 10:33

0 Answers0