2014-04-14 25 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

「歡迎來到無論如何是誰的代碼,語法被搞砸了,網站的地方沒有關係」 –