Dane O'Connor
Dane O'Connor

Reputation: 77378

How do I build dynamic functions with javascript?

I'm getting myself confused with all these languages! :)

// given this function
var f = function(a,b) { return a == b; }

// and these values for a
var a = [1,2,3]

// how do I make this array (a is replaced by its value)?
var results = [
   function(b) { return 1 == b; },
   function(b) { return 2 == b; },
   function(b) { return 3 == b; }
]

Upvotes: 0

Views: 83

Answers (1)

Dave Newton
Dave Newton

Reputation: 160321

function build(a) {
    return function(b) { return a == b; }
}

var results = [];
var a = [1, 2, 3];

for (var i = 0; i < a.length; i++) {
    results.push(build(a[i]));
}    

Some output:

> results[0](1)
true
> results[0](2)
false
> results[1](1)
false
> results[1](2)
true

Upvotes: 2

Related Questions