0

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;
}
Community
  • 1
  • 1
danielho
  • 17
  • 3
  • 2
    Where did `temp` come from? Also, you're not following the spec; isn't the problem to throw functions into the global namespace instead of returning an array? But if that is what you meant to do, and you get to use ES5 methods: `return array.map(function(v) { return function() { return v; }; });` – Ry- Jan 15 '13 at 04:03

4 Answers4

1
function transform(array) {

  b = [];
  var i;
  for (i = 0; i < array.length; i += 1) {
    b[i] = (function (x) { 
              return function () { return x; };
            })(array[i]);
  }
  return b;
}

demo http://jsbin.com/udasoj/1/edit

Hogan
  • 69,564
  • 10
  • 76
  • 117
0

Your code is correct if you call b[0](), then you should get the value returned.

ryudice
  • 36,476
  • 32
  • 115
  • 163
0

What is temp? It looks like the way to accomplish this is to generate the function via another function:

function transform(array) {
  b = [];
  var i;
  for (i = 0; i < array.length; i += 1) {
     b[i] = createReturnFunction(a[i]);
    };
  }

  return b;
}

function createReturnFunction(value){
  return function(){ return value; }; 
}

Working Fiddle: http://jsfiddle.net/eFWyf/

JLRishe
  • 99,490
  • 19
  • 131
  • 169
0

Note that none of the existing answers will quite work; they will all produce functions that return that last value in a. var is function-scoped and interacts poorly with closures.

See this other answer I just wrote, which explains a similar problem: https://stackoverflow.com/a/14330595/17875

Community
  • 1
  • 1
Eevee
  • 47,412
  • 11
  • 95
  • 127