国产毛多水多高潮高清,久热这里只有精品视频6,国内精品久久久久久久久电影网,国产男同志CHINA69,精品999日本久久久影院,人人妻人人澡人人爽人人精品,亚洲中文无码永久免

js 函数式编程:不要再使用 for 循环啦,试试 map 吧-买彩票中奖的人

js 函数式编程:不要再使用 for 循环啦,试试 map 吧

2026-01-18 11:53:50投稿人:大發(fā)BET手機(jī)網(wǎng)頁(yè)版(濟(jì)寧)有限公司圍觀367863 評(píng)論

js 函數(shù)式編程:不要再使用 for 循環(huán)啦 ,試試 map 吧

楔子

在 JavaScript 中 ,由于 Function 本質(zhì)也是對(duì)象(這與 Haskell 中【函數(shù)的本質(zhì)是值】思路一致),所以我們可以把 Function 作為參數(shù)來(lái)進(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

又得講這個(gè)老生常談的定義:如果一個(gè)函數(shù)“接收函數(shù)作為參數(shù)”或“返回函數(shù)作為輸出” ,那么這個(gè)函數(shù)被稱作“高階函數(shù)”;

本篇要談的是 :高階函數(shù)中的 map、filter、reduce 是【如何實(shí)踐】的,我愿稱之為 :高階映射!!

先別覺(jué)得這東西陌生,其實(shí)咱們天天都見(jiàn) !!

例 :

[1,2,3].map(item =>item*2)

實(shí)踐

Talk is cheap. Show me the code.

以下有 4 組代碼,每組的 2 個(gè)代碼片段實(shí)現(xiàn)目標(biāo)一致,但實(shí)現(xiàn)方式有異 ,感受感受 ,你更喜歡哪個(gè) ?

第 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); // 25

2

const arr = [5, 7, 1, 8, 4];const sum = arr.reduce(function(accumulator, currentValue) {   return accumulator + currentValue;});console.log(sum); // 25

更喜歡哪個(gè)  ?有答案了嗎