1. <ul id="0c1fb"></ul>

      <noscript id="0c1fb"><video id="0c1fb"></video></noscript>
      <noscript id="0c1fb"><listing id="0c1fb"><thead id="0c1fb"></thead></listing></noscript>

      99热在线精品一区二区三区_国产伦精品一区二区三区女破破_亚洲一区二区三区无码_精品国产欧美日韩另类一区

      RELATEED CONSULTING
      相關(guān)咨詢
      選擇下列產(chǎn)品馬上在線溝通
      服務(wù)時(shí)間:8:30-17:00
      你可能遇到了下面的問題
      關(guān)閉右側(cè)工具欄

      新聞中心

      這里有您想知道的互聯(lián)網(wǎng)營(yíng)銷解決方案
      數(shù)組reduce高級(jí)用法有哪些

      本篇內(nèi)容介紹了“數(shù)組reduce高級(jí)用法有哪些”的有關(guān)知識(shí),在實(shí)際案例的操作過程中,不少人都會(huì)遇到這樣的困境,接下來就讓小編帶領(lǐng)大家學(xué)習(xí)一下如何處理這些情況吧!希望大家仔細(xì)閱讀,能夠?qū)W有所成!

      加格達(dá)奇網(wǎng)站制作公司哪家好,找創(chuàng)新互聯(lián)建站!從網(wǎng)頁(yè)設(shè)計(jì)、網(wǎng)站建設(shè)、微信開發(fā)、APP開發(fā)、響應(yīng)式網(wǎng)站設(shè)計(jì)等網(wǎng)站項(xiàng)目制作,到程序開發(fā),運(yùn)營(yíng)維護(hù)。創(chuàng)新互聯(lián)建站自2013年創(chuàng)立以來到現(xiàn)在10年的時(shí)間,我們擁有了豐富的建站經(jīng)驗(yàn)和運(yùn)維經(jīng)驗(yàn),來保證我們的工作的順利進(jìn)行。專注于網(wǎng)站建設(shè)就選創(chuàng)新互聯(lián)建站

      背景

      reduce作為ES5新增的常規(guī)數(shù)組方法之一,對(duì)比forEach、filter和map,在實(shí)際使用上好像有些被忽略,發(fā)現(xiàn)身邊的人極少使用它,導(dǎo)致這個(gè)如此強(qiáng)大的方法被逐漸埋沒。

      如果經(jīng)常使用reduce,怎么可能放過如此好用的它呢!我還是得把他從塵土中取出來擦干凈,奉上它的高級(jí)用法給大家。一個(gè)如此好用的方法不應(yīng)該被大眾埋沒。

      下面對(duì)reduce的語法進(jìn)行簡(jiǎn)單說明,詳情可查看MDN的reduce()的相關(guān)說明。

      •  定義:對(duì)數(shù)組中的每個(gè)元素執(zhí)行一個(gè)自定義的累計(jì)器,將其結(jié)果匯總為單個(gè)返回值

      •  形式:array.reduce((t, v, i, a) => {}, initValue)

      •  參數(shù)

        •   callback:回調(diào)函數(shù)(必選)

        •   initValue:初始值(可選)

      •  回調(diào)函數(shù)的參數(shù)

        •   total(t):累計(jì)器完成計(jì)算的返回值(必選)

        •   value(v):當(dāng)前元素(必選)

        •   index(i):當(dāng)前元素的索引(可選)

        •   array(a):當(dāng)前元素所屬的數(shù)組對(duì)象(可選)

      •  過程

        •   以t作為累計(jì)結(jié)果的初始值,不設(shè)置t則以數(shù)組第一個(gè)元素為初始值

        •   開始遍歷,使用累計(jì)器處理v,將v的映射結(jié)果累計(jì)到t上,結(jié)束此次循環(huán),返回t

        •   進(jìn)入下一次循環(huán),重復(fù)上述操作,直至數(shù)組最后一個(gè)元素

        •   結(jié)束遍歷,返回最終的t

      reduce的精華所在是將累計(jì)器逐個(gè)作用于數(shù)組成員上,把上一次輸出的值作為下一次輸入的值。下面舉個(gè)簡(jiǎn)單的栗子,看看reduce的計(jì)算結(jié)果。

      const arr = [3, 5, 1, 4, 2];  const a = arr.reduce((t, v) => t + v);  // 等同于  const b = arr.reduce((t, v) => t + v, 0);

      reduce實(shí)質(zhì)上是一個(gè)累計(jì)器函數(shù),通過用戶自定義的累計(jì)器對(duì)數(shù)組成員進(jìn)行自定義累計(jì),得出一個(gè)由累計(jì)器生成的值。另外reduce還有一個(gè)胞弟reduceRight,兩個(gè)方法的功能其實(shí)是一樣的,只不過reduce是升序執(zhí)行,reduceRight是降序執(zhí)行。

      對(duì)空數(shù)組調(diào)用reduce()和reduceRight()是不會(huì)執(zhí)行其回調(diào)函數(shù)的,可認(rèn)為reduce()對(duì)空數(shù)組無效

      高級(jí)用法

      單憑以上一個(gè)簡(jiǎn)單栗子不足以說明reduce是個(gè)什么。為了展示reduce的魅力,我為大家提供25種場(chǎng)景來應(yīng)用reduce的高級(jí)用法。有部分高級(jí)用法可能需要結(jié)合其他方法來實(shí)現(xiàn),這樣為reduce的多元化提供了更多的可能性。

      部分示例代碼的寫法可能有些騷,看得不習(xí)慣可自行整理成自己的習(xí)慣寫法

      • 累加累乘 

      function Accumulation(...vals) {      return vals.reduce((t, v) => t + v, 0);  }  function Multiplication(...vals) {      return vals.reduce((t, v) => t * v, 1);  }
      Accumulation(1, 2, 3, 4, 5); // 15  Multiplication(1, 2, 3, 4, 5); // 120
      • 權(quán)重求和 

      const scores = [      { score: 90, subject: "chinese", weight: 0.5 },      { score: 95, subject: "math", weight: 0.3 },      { score: 85, subject: "english", weight: 0.2 }  ];  const result = scores.reduce((t, v) => t + v.score * v.weight, 0); // 90.5
      • 代替reverse 

      function Reverse(arr = []) {      return arr.reduceRight((t, v) => (t.push(v), t), []);  }
      Reverse([1, 2, 3, 4, 5]); // [5, 4, 3, 2, 1]
      • 代替map和filter 

      const arr = [0, 1, 2, 3];  // 代替map:[0, 2, 4, 6]  const a = arr.map(v => v * 2);  const b = arr.reduce((t, v) => [...t, v * 2], []);  // 代替filter:[2, 3]  const c = arr.filter(v => v > 1);  const d = arr.reduce((t, v) => v > 1 ? [...t, v] : t, []);  // 代替map和filter:[4, 6]  const e = arr.map(v => v * 2).filter(v => v > 2);  const f = arr.reduce((t, v) => v * 2 > 2 ? [...t, v * 2] : t, []);
      • 代替some和every 

      const scores = [      { score: 45, subject: "chinese" },      { score: 90, subject: "math" },      { score: 60, subject: "english" }  ];  // 代替some:至少一門合格  const isAtLeastOneQualified = scores.reduce((t, v) => v.score >= 60, false); // true  // 代替every:全部合格  const isAllQualified = scores.reduce((t, v) => t && v.score >= 60, true); // false
      • 數(shù)組分割 

      function Chunk(arr = [], size = 1) {      return arr.length ? arr.reduce((t, v) => (t[t.length - 1].length === size ? t.push([v]) : t[t.length - 1].push(v), t), [[]]) : [];  }
      const arr = [1, 2, 3, 4, 5];  Chunk(arr, 2); // [[1, 2], [3, 4], [5]]
      • 數(shù)組過濾 

      function Difference(arr = [], oarr = []) {      return arr.reduce((t, v) => (!oarr.includes(v) && t.push(v), t), []);  }
      const arr1 = [1, 2, 3, 4, 5];  const arr2 = [2, 3, 6]  Difference(arr1, arr2); // [1, 4, 5]
      • 數(shù)組填充 

      function Fill(arr = [], val = "", start = 0, end = arr.length) {      if (start < 0 || start >= end || end > arr.length) return arr;      return [          ...arr.slice(0, start),          ...arr.slice(start, end).reduce((t, v) => (t.push(val || v), t), []),          ...arr.slice(end, arr.length)      ];  }
      const arr = [0, 1, 2, 3, 4, 5, 6];  Fill(arr, "aaa", 2, 5); // [0, 1, "aaa", "aaa", "aaa", 5, 6]
      • 數(shù)組扁平 

      function Flat(arr = []) {      return arr.reduce((t, v) => t.concat(Array.isArray(v) ? Flat(v) : v), [])  }
      const arr = [0, 1, [2, 3], [4, 5, [6, 7]], [8, [9, 10, [11, 12]]]];  Flat(arr); // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
      • 數(shù)組去重 

      function Uniq(arr = []) {      return arr.reduce((t, v) => t.includes(v) ? t : [...t, v], []);  }
      const arr = [2, 1, 0, 3, 2, 1, 2];  Uniq(arr); // [2, 1, 0, 3]
      • 數(shù)組最大最小值 

      function Max(arr = []) {      return arr.reduce((t, v) => t > v ? t : v);  }  function Min(arr = []) {      return arr.reduce((t, v) => t < v ? t : v);  }
      const arr = [12, 45, 21, 65, 38, 76, 108, 43];  Max(arr); // 108  Min(arr); // 12
      • 數(shù)組成員獨(dú)立拆解 

      function Unzip(arr = []) {      return arr.reduce(          (t, v) => (v.forEach((w, i) => t[i].push(w)), t),          Array.from({ length: Math.max(...arr.map(v => v.length)) }).map(v => [])      );  }
      const arr = [["a", 1, true], ["b", 2, false]];  Unzip(arr); // [["a", "b"], [1, 2], [true, false]]
      • 數(shù)組成員個(gè)數(shù)統(tǒng)計(jì) 

      function Count(arr = []) {      return arr.reduce((t, v) => (t[v] = (t[v] || 0) + 1, t), {});  }
      const arr = [0, 1, 1, 2, 2, 2];  Count(arr); // { 0: 1, 1: 2, 2: 3 }
      此方法是字符統(tǒng)計(jì)和單詞統(tǒng)計(jì)的原理,入?yún)r(shí)把字符串處理成數(shù)組即可
      • 數(shù)組成員位置記錄 

      function Position(arr = [], val) {      return arr.reduce((t, v, i) => (v === val && t.push(i), t), []);  }
      const arr = [2, 1, 5, 4, 2, 1, 6, 6, 7];  Position(arr, 2); // [0, 4]
      • 數(shù)組成員特性分組 

      function Group(arr = [], key) {      return key ? arr.reduce((t, v) => (!t[v[key]] && (t[v[key]] = []), t[v[key]].push(v), t), {}) : {};  }
      const arr = [      { area: "GZ", name: "YZW", age: 27 },      { area: "GZ", name: "TYJ", age: 25 },      { area: "SZ", name: "AAA", age: 23 },      { area: "FS", name: "BBB", age: 21 },      { area: "SZ", name: "CCC", age: 19 }  ]; // 以地區(qū)area作為分組依據(jù)  Group(arr, "area"); // { GZ: Array(2), SZ: Array(2), FS: Array(1) }
      • 數(shù)組成員所含關(guān)鍵字統(tǒng)計(jì) 

      function Keyword(arr = [], keys = []) {      return keys.reduce((t, v) => (arr.some(w => w.includes(v)) && t.push(v), t), []);  }
      const text = [      "今天天氣真好,我想出去釣魚",      "我一邊看電視,一邊寫作業(yè)",      "小明喜歡同桌的小紅,又喜歡后桌的小君,真TM花心",      "最近上班喜歡摸魚的人實(shí)在太多了,代碼不好好寫,在想入非非"  ];  const keyword = ["偷懶", "喜歡", "睡覺", "摸魚", "真好", "一邊", "明天"];  Keyword(text, keyword); // ["喜歡", "摸魚", "真好", "一邊"]
      • 字符串翻轉(zhuǎn) 

      function ReverseStr(str = "") {      return str.split("").reduceRight((t, v) => t + v);  }
      const str = "reduce最牛逼";  ReverseStr(str); // "逼牛最ecuder"
      • 數(shù)字千分化 

      function ThousandNum(num = 0) {      const str = (+num).toString().split(".");      const int = nums => nums.split("").reverse().reduceRight((t, v, i) => t + (i % 3 ? v : `${v},`), "").replace(/^,|,$/g, "");      const dec = nums => nums.split("").reduce((t, v, i) => t + ((i + 1) % 3 ? v : `${v},`), "").replace(/^,|,$/g, "");      return str.length > 1 ? `${int(str[0])}.${dec(str[1])}` : int(str[0]);  }
      ThousandNum(1234); // "1,234"  ThousandNum(1234.00); // "1,234"  ThousandNum(0.1234); // "0.123,4"  ThousandNum(1234.5678); // "1,234.567,8"
      • 異步累計(jì) 

      async function AsyncTotal(arr = []) {      return arr.reduce(async(t, v) => {          const at = await t;          const todo = await Todo(v);          at[v] = todo;          return at;      }, Promise.resolve({}));  }
      const result = await AsyncTotal(); // 需要在async包圍下使用
      • 斐波那契數(shù)列 

      function Fibonacci(len = 2) {      const arr = [...new Array(len).keys()];      return arr.reduce((t, v, i) => (i > 1 && t.push(t[i - 1] + t[i - 2]), t), [0, 1]);  }
      Fibonacci(10); // [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
      • URL參數(shù)反序列化 

      function ParseUrlSearch() {      return location.search.replace(/(^\?)|(&$)/g, "").split("&").reduce((t, v) => {          const [key, val] = v.split("=");          t[key] = decodeURIComponent(val);          return t;      }, {});  }
      // 假設(shè)URL為:https://www.baidu.com?age=25&name=TYJ  ParseUrlSearch(); // { age: "25", name: "TYJ" }
      • URL參數(shù)序列化 

      function StringifyUrlSearch(search = {}) {      return Object.entries(search).reduce(          (t, v) => `${t}${v[0]}=${encodeURIComponent(v[1])}&`,          Object.keys(search).length ? "?" : ""      ).replace(/&$/, "");  }
      StringifyUrlSearch({ age: 27, name: "YZW" }); // "?age=27&name=YZW"
      • 返回對(duì)象指定鍵值 

      function GetKeys(obj = {}, keys = []) {      return Object.keys(obj).reduce((t, v) => (keys.includes(v) && (t[v] = obj[v]), t), {});  }
      const target = { a: 1, b: 2, c: 3, d: 4 };  const keyword = ["a", "d"];  GetKeys(target, keyword); // { a: 1, d: 4 }
      • 數(shù)組轉(zhuǎn)對(duì)象 

      const people = [      { area: "GZ", name: "YZW", age: 27 },      { area: "SZ", name: "TYJ", age: 25 }  ];  const map = people.reduce((t, v) => {      const { name, ...rest } = v;      t[name] = rest;      return t;  }, {}); // { YZW: {…}, TYJ: {…} }
      • Redux Compose函數(shù)原理 

      function Compose(...funs) {      if (funs.length === 0) {          return arg => arg;      }      if (funs.length === 1) {          return funs[0];      }      return funs.reduce((t, v) => (...arg) => t(v(...arg)));  }

      兼容和性能

      好用是挺好用的,但是兼容性如何呢?在Caniuse上搜索一番,兼容性絕對(duì)的好,可大膽在任何項(xiàng)目上使用。不要吝嗇你的想象力,盡情發(fā)揮reduce的compose技能啦。對(duì)于時(shí)常做一些累計(jì)的功能,reduce絕對(duì)是首選方法。

      數(shù)組reduce高級(jí)用法有哪些

      數(shù)組reduce高級(jí)用法有哪些

      另外,有些同學(xué)可能會(huì)問,reduce的性能又如何呢?下面我們通過對(duì)for-in、forEach、map和reduce四個(gè)方法同時(shí)做1~100000的累加操作,看看四個(gè)方法各自的執(zhí)行時(shí)間。

      // 創(chuàng)建一個(gè)長(zhǎng)度為100000的數(shù)組  const list = [...new Array(100000).keys()];  // for-in  console.time("for-in");  let result1 = 0;  for (let i = 0; i < list.length; i++) {      result1 += i + 1;  }  console.log(result1);  console.timeEnd("for-in");  // forEach  console.time("forEach");  let result2 = 0;  list.forEach(v => (result2 += v + 1));  console.log(result2);  console.timeEnd("forEach");  // map  console.time("map");  let result3 = 0;  list.map(v => (result3 += v + 1, v));  console.log(result3);  console.timeEnd("map");  // reduce  console.time("reduce");  const result4 = list.reduce((t, v) => t + v + 1, 0);  console.log(result4);  console.timeEnd("reduce");
      累加操作執(zhí)行時(shí)間
      for-in6.719970703125ms
      forEach3.696044921875ms
      map3.554931640625ms
      reduce2.806884765625ms

      以上代碼在MacBook Pro 2019 15寸 16G內(nèi)存 512G閃存的Chrome 79下執(zhí)行,不同的機(jī)器不同的環(huán)境下執(zhí)行以上代碼都有可能存在差異。

      “數(shù)組reduce高級(jí)用法有哪些”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識(shí)可以關(guān)注創(chuàng)新互聯(lián)網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實(shí)用文章!


      當(dāng)前文章:數(shù)組reduce高級(jí)用法有哪些
      分享網(wǎng)址:http://ef60e0e.cn/article/ghiehi.html
      99热在线精品一区二区三区_国产伦精品一区二区三区女破破_亚洲一区二区三区无码_精品国产欧美日韩另类一区
      1. <ul id="0c1fb"></ul>

        <noscript id="0c1fb"><video id="0c1fb"></video></noscript>
        <noscript id="0c1fb"><listing id="0c1fb"><thead id="0c1fb"></thead></listing></noscript>

        淮滨县| 金乡县| 孙吴县| 广东省| 四川省| 山丹县| 昆明市| 富宁县| 民乐县| 宁远县| 霍州市| 文登市| 铁岭市| 紫金县| 理塘县| 徐闻县| 泸水县| 同江市| 家居| 双江| 鹤岗市| 长武县| 德保县| 灌南县| 中方县| 香港 | 安国市| 高淳县| 原阳县| 三原县| 富蕴县| 镇安县| 河西区| 周口市| 内黄县| 宿州市| 南靖县| 万州区| 吉林市| 甘肃省| 富川|