Method # 1
function transform(ar) {
var alStr = [];
for(var i=0; i<ar.length; i++) {
alStr[i] = (function(v) {
return (function() {
return v;
});
}(ar[i]));
}
return alStr;
}
var a = ["a", 24, { foo: "bar" }];
var b = transform(a);
a[1];
b[1]();
Method # 2
function transform(ar) {
var alStr = [];
for(var a in ar) {
var O = function() {
return a;
}
alStr.push(O);
}
return alStr;
}
var a = ["a", 24, { foo: "bar" }];
var b = transform(a);
a[1];
b[1]();
The above mentioned methods are used to convert an array objects into individual functions which on execution return the specific array object. Want to know why method #1 works and method #2 doesnt.
var abefore theforloop, and it'll do a better job of reflecting reality. There are no variables that are local to theforstatement, because in JavaScript, scope is always defined by afunction. This means all the functions being created in theforloop are referring to the sameavariable, which is local to thetransformfunction.