Method # 1
function transform(ar) {
var alStr = [];
for(var i=0; i
In Method #2 there are two problems:
You are returning the key name, a
, rather than the array value, ar[a]
. That is, rather than return a;
you want return ar[a];
.
The function will always refer to the last value looped through because it references the same scope object. To create a new scope object you will need a closure, a with
block, or a bound function.
With a closure:
for(var a in ar) {
var O = (function(val) {
return function() {
return val;
}
})(ar[a]);
alStr.push(O);
}
With a with
block:
for(var a in ar) {
with({val: ar[a]}) {
alStr.push(function() {
return val;
});
}
}
With a bound function:
for(var a in ar) {
var O = function(x) { return x; };
alStr.push(O.bind(null, arr[a]));
}