溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

如何使用JS函數(shù)式編程Reduce與Map

發(fā)布時間:2021-10-18 11:08:55 來源:億速云 閱讀:183 作者:iii 欄目:web開發(fā)

本篇內(nèi)容主要講解“如何使用JS函數(shù)式編程Reduce與Map”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學(xué)習(xí)“如何使用JS函數(shù)式編程Reduce與Map”吧!

JavaScript是當(dāng)今流行語言中對函數(shù)式編程支持最好的編程語言。函數(shù)式編程的七個函數(shù)分別為:

- reduce() and reduceRight() to apply an operation to a whole array, reducing it to a single result - map() to transform one array into another by applying a function to each of its elements - flat() to make a single array out of an array of arrays - flatMap() to mix together mapping and flattening - forEach() to simplify writing loops by abstracting the necessary looping code

以及 search 與 selection 的函數(shù):

- filter() to pick some elements from an array - find() and findIndex() to search for elements that satisfy a condition - A pair of predicates, every() and some(), to check an array for a Boolean test

一、array.reduce() 將數(shù)列降維至一個值

當(dāng)我們處理array的時候,總是陷入到無窮盡的loop循環(huán)之中,掉入進瑣碎的陷阱,戕害我們的思維和大腦。

reduce的基本工作原理如下:

如何使用JS函數(shù)式編程Reduce與Map

求數(shù)列的和

首先從耳熟能詳?shù)那髷?shù)列之和起步。

const myArray = [22, 9, 60, 12, 4, 56]; const sum = (x, y) => x + y; const mySum = myArray.reduce(sum, 0); // 163

觀察其運行軌跡:

#+begin_src js :results output const myArray = [22, 9, 60, 12, 4, 56]; const sumAndLog = (x, y) => {  console.log(`${x}+${y}=${x + y}`);   return x + y; }; myArray.reduce(sumAndLog, 0);  #+end_src  #+RESULTS: : 0+22=22 : 22+9=31 : 31+60=91 : 91+12=103 : 103+4=107 : 107+56=163

求均值

有了reduce,我們得以用“描述”的方式,以decalratively的方式求得average:

const average = arr => arr.reduce(sum, 0) / arr.length; console.log(average(myArray)); // 27.166667

求均值的第二種方法,將length寫到里面:

const average2 = (sum, val, ind, arr) => {   sum += val;   return ind === arr.length - 1 ? sum / arr.length          : sum; //將這作為思考的原材料 };  console.log(myArray.reduce(average2, 0)); // 27.166667s

更近一步,將average作為固有屬性:

Array.prototype.average = function() {   return this.reduce((x, y) => x + y, 0) / this.length; };  let myAvg = [22, 9, 60, 12, 4, 56].average(); // 27.166667

單詞計算多個值

雖然 reduce 只能返回單個結(jié)果,但是此返回結(jié)果卻可以包含多個元素,比如是object。

const average3 = arr => {   const sumCount = arr.reduce(     (accum, value) => ({sum: value + accum.sum, count: accum.count + 1}),     {sum: 0, count: 0}   );    return sumCount.sum / sumCount.count; };  console.log(average3([7, 11, 19, 23]));

以array的方式改寫:

const average4 = arr => {   const sumCount = arr.reduce(     (accum, value) => [accum[0] + value, xaccum[1] + 1],     [0, 0]   );   return sumCount[0] / sumCount[1]; };  console.log(average4(myArray)); // 27.166667

從右往左的折疊

工作原理如下圖:

如何使用JS函數(shù)式編程Reduce與Map

比如 reverse 字符串的常規(guī)解決方案為:

const reverseString = str => {   let arr = str.split("");   arr.reverse();   return arr.join(""); };  console.log(reverseString("MONTEVIDEO"));  // OEDIVETNOM

而reduceRight的解題方案呢,

const reverseString2 = str =>   str.split("").reduceRight((x, y) => x + y, "");  console.log(reverseString2("OEDIVETNOM"));  // MONTEVID

二、array.map 從數(shù)學(xué)到編程

map首先是數(shù)學(xué)上的概念。

如何使用JS函數(shù)式編程Reduce與Map

從object中提取數(shù)據(jù)

const markers = [   {name: "AR", lat: -34.6, lon: -58.4},   {name: "BO", lat: -16.5, lon: -68.1},   {name: "BR", lat: -15.8, lon: -47.9},   {name: "CL", lat: -33.4, lon: -70.7},   {name: "CO", lat:   4.6, lon: -74.0},   {name: "EC", lat:  -0.3, lon: -78.6},   {name: "PE", lat: -12.0, lon: -77.0},   {name: "PY", lat: -25.2, lon: -57.5},   {name: "UY", lat: -34.9, lon: -56.2},   {name: "VE", lat:  10.5, lon: -66.9}, ];  let averageLat = average(markers.map(x => x.lat)); // -15.76 let averageLon = average(markers.map(x => x.lon)); // -65.53 // extended array.prototype let averageLat2 = markers.map(x => x.lat).average(); let averageLon2 = markers.map(x => x.lon).average();

悄無聲息的處理數(shù)據(jù)

看一個我們想當(dāng)然的應(yīng)用:

["123.45", "67.8", "90"].map(parseFloat); // [123.45, 67.8, 90]  ["123.45", "-67.8", "90"].map(parseInt); // [123, NaN, NaN]

這是因為 parseInt 有一個 optional 的參數(shù) radix。

數(shù)列的表示方法

現(xiàn)在我們來創(chuàng)建一個 range.

const range = (start, stop) =>   new Array(stop - start).fill(0).map((v, i) => start + i); // 必須寫一個v,也必須寫 new let from2To6 = range(2, 7); // [2, 3, 4, 5, 6]

嘗試求乘方:

const range = (start, stop) =>   new Array(stop - start).fill(0).map((v, i) => start + i);  const factorialByRange = n => range(1, n + 1).reduce((x, y) => x * y, 1);  factorialByRange(5); // 120 factorialByRange(3);

嘗試字母表:

const ALPHABET = range("A".charCodeAt(), "Z".charCodeAt() + 1).map(x =>   String.fromCharCode(x) );  // ["A", "B", "C", ... "X", "Y", "Z"]

用 reduce 構(gòu)造 map

reduce是所有其他函數(shù)的起點,

const myMap = (arr, fn) => arr.reduce((x, y) => x.concat(fn(y)), []);

嘗試兩種不同的解決方案:

const myArray = [22, 9, 60, 12, 4, 56]; const dup = x => 2 * x;  console.log(myArray.map(dup));    // [44, 18, 120, 24, 8, 112] console.log(myMap(myArray, dup)); // [44, 18, 120, 24, 8, 112] console.log(myArray);             // [22, 9, 60, 12, 4, 56]

到此,相信大家對“如何使用JS函數(shù)式編程Reduce與Map”有了更深的了解,不妨來實際操作一番吧!這里是億速云網(wǎng)站,更多相關(guān)內(nèi)容可以進入相關(guān)頻道進行查詢,關(guān)注我們,繼續(xù)學(xué)習(xí)!

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI