1

I have code that looks like this:

var a = [];
for(var i = 0; i < 10; i++) {
    a[i] = function() {
        console.log(i);
    }
}

Unfortunately, it seems that i is being passed by reference, so all the functions in a output 10. How do I make it so that each function outputs the value that i had when it was created? I.e. a[0]() gives 0, a[1]() gives 1, etc.

EDIT: to clarify, I do not want a to store the values 0-9. I want a to store functions that return the values 0-9.

Bluefire
  • 13,519
  • 24
  • 74
  • 118

2 Answers2

5

You need to invoke a function (to create a closure that captures your value) which returns a function (the one you want to end up with). Something like this:

var a = [];
for (var i = 0; i < 10; i++) {
    a[i] = (function(value) {
        return function() {
            console.log(value);
        }
    })(i);
}
Ghazgkull
  • 970
  • 1
  • 6
  • 17
0
var a = [];
for(var i = 0; i < 10; i++) {
    a[i] = (function(j) {
        return function () {
            console.log(j);
        }
    })(i);
}

A better performing version -

function makeFunction(i) {
    return function () {
        console.log(i);
    }
}

var a = [];
for(var i = 0; i < 10; i++) {
    a[i] = makeFunction(i);
}

JSFiddle Demo.

MD Sayem Ahmed
  • 28,628
  • 27
  • 111
  • 178