将数组的元素应用于函数javascript

时间:2014-09-25 11:09:13

标签: javascript arrays

我是Javascript中的新手,我尝试将一个函数应用于数组的每个元素,然后递归返回输出。你能帮助我吗?我有循环去想数组的元素,但我不知道签名适用于他们的功能。这是我的代码部分:

function mapReduce(f, a, seed) {
     for(i = 0; i != a.length; i++){

    }
}

其中f是函数,a是数组,seed是我必须在末尾添加的值(我必须对输出求和,然后添加种子参数)。希望您能够帮助我。对不起,如果问题可能导致愚蠢

var itemize = function(x) {
    if(x == undefined){
        return undefined
    } else {
    var str = "<li>";
    var fin = "</li>";
    return str + x + fin;
    }
 };

测试是:

equal(mapReduce(itemize, ["A","B","C"]), "<.li>A<./li><.li>B<./li><.li>C<./li>" ,    "MapReduce(itemize, ['A','B','C']) should yield '<.li>A<./li><.li>B<./li><.li>C<./li>'")

为了减少地图,我做了类似的事情:

 function mapReduce(f, a, seed) {
 for(i = 0; i != a.length; i++){
    if(seed != undefined){
        if(a != undefined) {
            seed = seed + f(a[i]);
        } else {
            return undefined;
        }
    } else {
        var d = "";
        d = d + f(a[i]);
    }

}
return seed;
}

1 个答案:

答案 0 :(得分:1)

您似乎希望mapReduce功能等同于

a.map(f).reduce(function(prev, item) {
    return item == undefined ? prev : prev + item;
}, seed == undefined ? "" : seed)

如果要在专用函数中组合此行为,请删除中间数组并使for-loop显式出现

function mapCombineString(f, a, seed) {
    if (!f || !a) return; // throw new TypeError() would be appropriate
    if (seed == undefined)
        seed = "";
    for (var i = 0; i != a.length; i++) {
        var item = f(a[i], i, a);
        if (item != undefined)
            seed = seed + f(a[i]);
    }
    return seed;
}