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

創(chuàng)新互聯(lián)服務(wù)項(xiàng)目包括豐南網(wǎng)站建設(shè)、豐南網(wǎng)站制作、豐南網(wǎng)頁制作以及豐南網(wǎng)絡(luò)營銷策劃等。多年來,我們專注于互聯(lián)網(wǎng)行業(yè),利用自身積累的技術(shù)優(yōu)勢、行業(yè)經(jīng)驗(yàn)、深度合作伙伴關(guān)系等,向廣大中小型企業(yè)、政府機(jī)構(gòu)等提供互聯(lián)網(wǎng)行業(yè)的解決方案,豐南網(wǎng)站推廣取得了明顯的社會效益與經(jīng)濟(jì)效益。目前,我們服務(wù)的客戶以成都為中心已經(jīng)輻射到豐南省份的部分城市,未來相信會繼續(xù)擴(kuò)大服務(wù)區(qū)域并繼續(xù)獲得客戶的支持與信任!
- - 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ù)列降維至一個(gè)值
當(dāng)我們處理array的時(shí)候,總是陷入到無窮盡的loop循環(huán)之中,掉入進(jìn)瑣碎的陷阱,戕害我們的思維和大腦。
reduce的基本工作原理如下:
求數(shù)列的和
首先從耳熟能詳?shù)那髷?shù)列之和起步。
- const myArray = [22, 9, 60, 12, 4, 56];
- const sum = (x, y) => x + y;
- const mySum = myArray.reduce(sum, 0); // 163
觀察其運(yùn)行軌跡:
- #+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
單詞計(jì)算多個(gè)值
雖然 reduce 只能返回單個(gè)結(jié)果,但是此返回結(jié)果卻可以包含多個(gè)元素,比如是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
從右往左的折疊
工作原理如下圖:
比如 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é)上的概念。
從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ù)
看一個(gè)我們想當(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]
這是因?yàn)?parseInt 有一個(gè) optional 的參數(shù) radix。
數(shù)列的表示方法
現(xiàn)在我們來創(chuàng)建一個(gè) range.
- const range = (start, stop) =>
- new Array(stop - start).fill(0).map((v, i) => start + i);
- // 必須寫一個(gè)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ù)的起點(diǎn),
- 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]
【編輯推薦】
- Windows10這功能已如同殘廢!教你如何徹底關(guān)閉它
- C++和C++程序員誰先完蛋?
- 2021年值得關(guān)注的人工智能趨勢
- RAID磁盤陣列到底適不適合你?一文讀懂
- Windows 10是絕唱!微軟新系統(tǒng)開始換版本號了
新聞名稱:幫你精通JS:函數(shù)式編程的七件武器之Reduce與Map
本文地址:http://fisionsoft.com.cn/article/dpjdgec.html


咨詢
建站咨詢
