2014-04-14 45 views
1

我已经尝试了许多方法来获取父参数是在减少的回调函数可见,但我一定是失去了一些东西......与高阶回调参数减少

// Static 
var y = [0, 1, 2, 3, 4, 5, 6, 7].reduce(
    function(arr, x){ 
     arr.push(Math.pow(2, x)); 
     return arr},[]); 
console.log(y); 

// Dynamic 
var lambda = function(arr, func) { 
    return (function(f) { return arr.reduce(function(a, x) { 
     a.push(f(x)); 
     return a; 
    }, [])})(func); 
} 
var y = lambda([0, 1, 2, 3, 4, 5, 6, 7],function(x){return Math.pow(x);}); 
console.log(y); 

输出:

[1, 2, 4, 8, 16, 32, 64, 128] 
[NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN] 

DEMO @ JSFiddle

+0

你说的'父parameter'是什么意思? – thefourtheye

+0

我想通过'func'对reduce函数进行显示。 –

+2

你是不是在'Math.pow(x)'中缺少'2'? – thefourtheye

回答

1

你缺少的参数之一Math.pow。你可能会想调用lambda这样

var y = lambda([0, 1, 2, 3, 4, 5, 6, 7], function(x) { 
    return Math.pow(2, x); 
}); 

而且,你不必到lambda建设与IIFE复杂化。它可以简单地

var lambda = function(arr, func) { 
    return arr.reduce(function(a, x) { 
     a.push(func(x)); 
     return a; 
    }, []); 
} 

编辑:正如你在评论建议你可以使用Array.prototype.map,这样

console.log(arr.map(function(x) { 
    return Math.pow(2, x); 
})); 
+0

虽然你回答第二,你首先回应。我会接受你的回答,但我会删除这篇文章,因为它是一个语法错误。 –

+1

@ Mr.Polywhirl:你不应该删除它,但我们可能会关闭它。 – Bergi

+0

好的,我会投票结束我自己的问题;-p –

1

不要在Math.pow忘了第一个参数:

// ------------------------------------------------------------v 
lambda([0, 1, 2, 3, 4, 5, 6, 7], function(x) { return Math.pow(2, x); }); 
+0

“欢迎来到无论如何是谁的代码,语法被搞砸了,网站的地方没有关系” –