简体   繁体   中英

Apply the elements of an array to a functions javascript

I'm new in Javascript and I'm try to apply a function to each element of an array and then return the output recursively. Can you help me? I have the loop to go thought the element of the array but I don't know the signature to apply to them the function. Here is my part of the code:

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

    }
}

Where f is the function, a is the array and seed is a value that I have to add at the end (I have to sum the output and then add the seed parameter). Hope you can help me. Sorry if the question could result stupid

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

The test is:

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>'")

For the map reduced I did something like this:

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

It seems like you want your mapReduce function to be equivalent to

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

If you want to combine this behaviour in a dedicated function, remove the intermediate array and make the for-loop explicit you would write

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM