高阶函数 filter map reduce _fei
高阶函数 filter map reduce
// 高阶函数 filter map reduce 用es6语法写demo // 过滤小于20的值,返回布尔值 true 或者 false // 循环数组中的每一个元素 //接受一个函数作为参数,这个函数作为一个累加器,从左到右遍历整个类型数组,最后返回一个单一的值 const nums = [10, 15, 18, 25, 34]; let newNums = nums.filter(item => item < 20) .map(item2 => item2 * 2) .reduce((total, item3) => total + item3); // filter 结束后 newNums = [10, 15, 18] // map 结束后 newsNums = [20, 30, 36]; // reduce 结束后 86
const nums = [10, 15, 18, 25, 34]; let newNum_1 = nums.filter(function (item1) { return item1 < 20; }); console.log(newNum_1); // [10, 15, 18] let newNum_2 = newNum_1.map(function (item2) { return item2 * 2; }); console.log(newNum_2); // [20, 30, 36] let newNum_3 = newNum_2.reduce(function (total, item3) { return total + item3; }) console.log(newNum_3); // 86
02) 获取对象中某个属性的所有值ES6
let obj = [ {name: "daFei", age: "18", hobby: "JavaScript"}, {name: "daFei", age: "18", hobby: "HTML"}, {name: "daFei", age: "18", hobby: "CSS"}, ]; let arr = obj.map(item => item.hobby); console.log(arr); // 输出 ["JavaScript", "HTML", "CSS"]
03) map保留原数组修改数据
let arr = [ {name: "daFei", age: "18", hobby: "JavaScript"}, {name: "daFei", age: "18", hobby: "HTML"}, {name: "daFei", age: "18", hobby: "CSS"}, ]; let arrNew = arr.map(item => { item.hobby = item.hobby + "__修改"; return item; }); console.log(arr, arrNew); let brr = [ {name: "daFei", age: "18", hobby: "JavaScript"}, {name: "daFei", age: "18", hobby: "HTML"}, {name: "daFei", age: "18", hobby: "CSS"}, ]; let brrNew = brr.map(item => { item = {...item, hobby: item.hobby + "__不改原数组"}; return item; }); console.log(brr, brrNew);
04) 其他函数
fill 填充数组
const item = { date: '2016-05-02', name: 'daFei', address: '北京', } Array(20).fill(item)
05) filter 2个数组双重循环去重
场景,对个一个数组去重,条件是根据另一个数组中的数据
// filter中 双重循环去重 const words1 = ['fei', 'foo', 'bar']; // 实际场景为对象数组 const words2 = ['fei']; let newArr = words1.filter(item => { const found = words2.findIndex(row => item === row) if (found === -1) { // 没有找到,说明当前值唯一 return true; } }) console.log(newArr); // 输出 ['foo', 'bar']