如何使用javascript构建动态函数?

时间:2012-01-27 17:48:35

标签: javascript function dynamic

我对所有这些语言感到困惑! :)

// 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; }
]

1 个答案:

答案 0 :(得分:2)

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]));
}    

一些输出:

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