前端 | 高阶函数(.filter .map .reduce)的使用总结

前端优化.png

"高阶函数是一个将一个或多个函数作为参数的函数" ——ClojureBridge

高阶函数可以帮助增强你的Javascript,使你的代码简单、简练、可读性强。

Array.prototype.filter()

filter()方法创建一个新数组,其包含是符合条件的元素
用法:

var words = ["spray", "limit", "elite", "exuberant", "destruction", "present"];

var longWords = words.filter(function ( word ) {

  //return true 则将该word push到longWords数组里
  //return false 则布会将改word   push到longWords数组里

    return word.length > 6;
});

  // Filtered array longWords is ["exuberant", "destruction", "present"]

在ES6中,可以使用箭头函数

var words = ["spray", "limit", "elite", "exuberant", "destruction", "present"];

var longWords = words.filter( word  =>  word.length > 6);

// Filtered array longWords is ["exuberant", "destruction", "present"]

Array.prototype.map()

map()方法创建一个新数组,其结果是该数组中的每个元素都调用一个提供的函数后返回的结果

用法:

var numbers = [1, 5, 10, 15];
var doubles = numbers.map(function(x) {
   return x * 2;
});
// doubles is now [2, 10, 20, 30]
// numbers is still [1, 5, 10, 15]

var numbers = [1, 4, 9];
var roots = numbers.map(Math.sqrt);
// roots is now [1, 2, 3]
// numbers is still [1, 4, 9]

Array.prototype.reduce()

reduce()方法适用于累加

var total = [0, 1, 2, 3].reduce(function(sum, value) {
    return sum + value;
}, 0);
  // total is 6

var flattened = [[0, 1], [2, 3], [4, 5]].reduce(function(a, b)
 {
//concat() 方法用于连接两个或多个数组
  return a.concat(b);
}, []);
// flattened is [0, 1, 2, 3, 4, 5]

你可能感兴趣的:(前端 | 高阶函数(.filter .map .reduce)的使用总结)