Possible Duplicate:
Javascript closure inside loops - simple practical example
You have an array of arbitrary values. Write a transform function in the global scope that will transform the array to an array of functions that return the original values, so instead of calling a[3], we will call a3.
For example I want:
var a = ["a", 24, { foo: "bar" }];
var b = transform(a);
a[1]; // 24
b[1](); // 24
However I am getting:
b
[function () {
return this.temp;
}, function () {
return this.temp;
}, function () {
return this.temp;
}]
Here is my code:
var a = ["a", 24, { foo: "bar" }];
var b = transform(a);
document.writeln(a[1]); // 24
document.writeln(b[0]()); // 24
document.writeln(b[1]()); // 24
function transform(array) {
b = [];
var i;
for (i = 0; i < array.length; i += 1) {
b[i] = function () {
return temp;
};
}
return b;
}