【问题标题】:Reduce with higher-order callback parameter [closed]使用高阶回调参数减少 [关闭]
【发布时间】:2014-04-14 11:50:06
【问题描述】:

我已经尝试了很多方法来让reduce的回调函数可以看到父参数,但是我一定遗漏了一些东西......

// 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

【问题讨论】:

  • parent parameter 是什么意思?
  • 我想将func 传递给reduce 函数。
  • 你不是在Math.pow(x) 中缺少2 吗?

标签: javascript callback reduce higher-order-functions


【解决方案1】:

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

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

此外,您不必使用 IIFE 使 lambda 构造复杂化。可以很简单

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

编辑:您自己在 cmets 中建议您可以使用 Array.prototype.map,像这样

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

【讨论】:

  • 虽然您第二个回答,但您还是第一个回答。我会接受你的回答,但我会删除这篇文章,因为它是语法错误。
  • @Mr.Polywhirl:你不应该删除它,但我们可能会关闭它。
  • 好的,我将投票结束我自己的问题;-p
  • 我才意识到我写了一个Array.map()函数...
  • @Mr.Polywhirl 大声笑,即使我现在也意识到了...... :) 也包括在答案中。
【解决方案2】:

不要忘记Math.pow 中的第一个参数:

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

【讨论】:

  • "欢迎来到这是谁的代码无论如何,语法被搞砸了,分数无关紧要的网站"
猜你喜欢
  • 2017-03-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-13
  • 2022-01-22
  • 2023-03-25
相关资源
最近更新 更多