乱人伦 国语对白海角社区,五月激情丁香婷婷综合中文字幕,欧美伊人婷婷久久五月综合,亚洲精品无amm毛片,亚洲男人第一无码AV网站,国产日韩欧美丝袜一区二区,亚洲一区精品在线观看

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

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

2026-01-18 03:01:45投稿人:HONG95990(宣城)有限公司圍觀9763 評(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í)踐】的 ,我愿稱之為 :高階映射!!

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

例:

[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è) ?有答案了嗎?

js 函數(shù)式編程<footer>
<div class=

感谢您访问我们的网站,您可能还对以下资源感兴趣:

乱人伦 国语对白海角社区,五月激情丁香婷婷综合中文字幕,欧美伊人婷婷久久五月综合,亚洲精品无amm毛片,亚洲男人第一无码AV网站,国产日韩欧美丝袜一区二区,亚洲一区精品在线观看