Array中的map(),filter()和reduce()

一、map()

map用于遍历数组中每一项的值,进行一系列的操作。

const prices = [19.99, 4.95, 25, 3.50];
let new_prices = [];
for(let i = 0; i < prices.length; i++) {
    new_prices.push(prices[i] * 1.06);
}

用map来书写会简单许多:

const prices= [19.99, 4.95, 25, 3.50];
let new_prices = prices.map(price => price *1.06);

二、filter()

fiter用于筛选数组中符合条件的值。

const numbers = [1,2,3,4,5,6,7,8];
let odds = [];
for(let i = 0; i < numbers.length; i++) {
    if(numbers[i] % 2 == 1) {
        odds.push(numbers[i]);
    }
}

用filter来书写会简单许多:

constnumbers = [1,2,3,4,5,6,7,8];
let odds = numbers.filter(num => num % 2);

三、reduce()

reduce是一个累加器,用于累加整个数组的值,可以有一个初始值。

const donations = [5, 20, 100, 80, 75];
let total = 10;
for(let i = 0; i < donations.length; i++) {
    total += donations[i];
}

用reduce来书写会简单许多:

const donations = [5, 20, 100, 80, 75];
let total = donations.reduce((total,donation)=> {
return total + donation;
}, 10);

reduce也经常被使用到函数组合中。

// demo flowRight  参考函数 g(f(x))  flowRight(g, f) ...args 为需要合并的函数 数组
function flowRight (...args){
    // value 为执行 函数的初始值
    return function (value) {
        return args.reverse().reduce(function (acc, func) {
            return func(acc)
        }, value)
    }
}
const compose = (...args) => value => args.reverse().reduce((acc, fnuc) => func(acc) , value)

猜你喜欢

转载自blog.csdn.net/qq_40289624/article/details/109572283