js 函数式编程:不要再使用 for 循环啦,试试 map 吧
js 函數(shù)式編程:不要再使用 for 循環(huán)啦,試試 map 吧
楔子
在 JavaScript 中,由于 Function 本質(zhì)也是對象(這與 Haskell 中【函數(shù)的本質(zhì)是值】思路一致),所以我們可以把 Function 作為參數(shù)來進(jìn)行傳遞 !
例:
function sayHi() { console.log("Hi");}function sayBye() { console.log("Bye");}function greet(type, sayHi, sayBye) { type === 1 ? sayHi() : sayBye()}greet(1, sayHi, sayBye); // Hi又得講這個老生常談的定義:如果一個函數(shù)“接收函數(shù)作為參數(shù)”或“返回函數(shù)作為輸出”,那么這個函數(shù)被稱作“高階函數(shù)”;
本篇要談的是:高階函數(shù)中的 map、filter、reduce 是【如何實(shí)踐】的 ,我愿稱之為:高階映射 !!
先別覺得這東西陌生,其實(shí)咱們天天都見!!
例:
[1,2,3].map(item =>item*2)實(shí)踐
Talk is cheap. Show me the code.
以下有 4 組代碼 ,每組的 2 個代碼片段實(shí)現(xiàn)目標(biāo)一致 ,但實(shí)現(xiàn)方式有異 ,感受感受,你更喜歡哪個?
第 1 組 :
1
const arr1 = [1, 2, 3];const arr2 = [];for(let i = 0; i < arr1.length; i++) { arr2.push(arr1[i] * 2);}console.log(arr2); // [ 2, 4, 6 ]2
const arr1 = [1, 2, 3];const arr2 = arr1.map(item =>item * 2);console.log(arr2); // [ 2, 4, 6 ]第 2 組 :
1
const birthYear = [1975, 1997, 2002, 1995, 1985];const ages = [];for(let i = 0; i < birthYear.length; i++) { let age = 2018 - birthYear[i]; ages.push(age);}console.log(ages); // [ 43, 21, 16, 23, 33 ]2
const birthYear = [1975, 1997, 2002, 1995, 1985];const ages = birthYear.map(year =>2018 - year);console.log(ages); // [ 43, 21, 16, 23, 33 ]第 3 組:
1
const persons = [ { name: 'Peter', age: 16 }, { name: 'Mark', age: 18 }, { name: 'John', age: 27 }, { name: 'Jane', age: 14 }, { name: 'Tony', age: 24},];const fullAge = [];for(let i = 0; i < persons.length; i++) { if(persons[i].age >= 18) { fullAge.push(persons[i]); }}console.log(fullAge);2
const persons = [ { name: 'Peter', age: 16 }, { name: 'Mark', age: 18 }, { name: 'John', age: 27 }, { name: 'Jane', age: 14 }, { name: 'Tony', age: 24},];const fullAge = persons.filter(person =>person.age >= 18);console.log(fullAge);第 4 組:
1
const arr = [5, 7, 1, 8, 4];let sum = 0;for(let i = 0; i < arr.length; i++) { sum = sum + arr[i];}console.log(sum); // 252
const arr = [5, 7, 1, 8, 4];const sum = arr.reduce(function(accumulator, currentValue) { return accumulator + currentValue;});console.log(sum); // 25更喜歡哪個