<kbd id="afajh"><form id="afajh"></form></kbd>
<strong id="afajh"><dl id="afajh"></dl></strong>
    <del id="afajh"><form id="afajh"></form></del>
        1. <th id="afajh"><progress id="afajh"></progress></th>
          <b id="afajh"><abbr id="afajh"></abbr></b>
          <th id="afajh"><progress id="afajh"></progress></th>

          10 個(gè)關(guān)于Reduce必須知道的 JavaScript 技巧

          共 5388字,需瀏覽 11分鐘

           ·

          2022-06-09 17:33

          英文 | https://javascript.plainenglish.io/10-must-know-javascript-tricks-tips-about-reduce-1368766d99da

          作為一個(gè)前端開發(fā)者,你一定會(huì)大量使用reduce函數(shù),它是一個(gè)強(qiáng)大而有用的數(shù)組API,但是,今天我想給大家分享10個(gè)關(guān)于它的進(jìn)階技巧。

          1、作為加法器和累加器

          使用“reduce”,我們可以輕松實(shí)現(xiàn)多個(gè)數(shù)相加或累加的功能。

          // adderconst sum = (...nums) => {  return nums.reduce((sum, num) => sum + num);};console.log(sum(1, 2, 3, 4, 10)); // 20// accumulatorconst accumulator = (...nums) => {  return nums.reduce((acc, num) => acc * num);};console.log(accumulator(1, 2, 3)); // 6

          2、計(jì)算一個(gè)數(shù)組的最大值和最小值

          有多少種方法可以得到數(shù)組的最大值或最小值?

          1):使用 Math.max 和 Math.min

          我們不得不承認(rèn),使用 Math 的 API 是最簡(jiǎn)單的方法。

          const array = [-1, 10, 6, 5];const max = Math.max(...array); // 10const min = Math.min(...array); // -1

          2):使用減少

          是的,只需一行代碼,我們就可以實(shí)現(xiàn)與 Math 的 API 相同的效果。

          const array = [-1, 10, 6, 5];const max = array.reduce((max, num) => (max > num ? max : num));const min = array.reduce((min, num) => (min < num ? min : num));

          3、格式化搜索參數(shù)

          獲取鏈接上的搜索參數(shù)是我們經(jīng)常要處理的事情。如何解析它們?

          例如:

          // url https://qianlongo.github.io/vue-demos/dist/index.html?name=fatfish&age=100#/home// format the search parameters{  "name": "fatfish",  "age": "100"}

          1)、正常方式

          這是大多數(shù)人使用它的方式。

          const parseQuery = () => {  const search = window.location.search;  let query = {};  search    .slice(1)    .split("&")    .forEach((it) => {      const [key, value] = it.split("=");      query[key] = decodeURIComponent(value);    });  return query;};

          2)、使用reduce

          Reduce 實(shí)際上可以做到這一點(diǎn),而且看起來更簡(jiǎn)單。

          const parseQuery = () => {  const search = window.location.search;  return search    .replace(/(^\?)|(&$)/g, "")    .split("&")    .reduce((query, it) => {      const [key, value] = it.split("=");      query[key] = decodeURIComponent(value);      return query;    }, {});};

          它是如何工作的?

          / url https://qianlongo.github.io/vue-demos/dist/index.html?name=fatfish&age=100#/home// 1. First get the search parameterconst search = window.location.search; // ?name=fatfish&age=100// 2. Remove the beginning "?" or ending "&".search.replace(/(^\?)|(&$)/g, "");// ?name=fatfish&age=100 => name=fatfish&age=100// 3. Use reduce to collect parameters// ...

          4、反序列化搜索參數(shù)

          當(dāng)我們要跳轉(zhuǎn)到某個(gè)鏈接并為其添加一些搜索參數(shù)時(shí),手動(dòng)拼接的方式不是很方便。

          如果要串聯(lián)的參數(shù)很多,那將是一場(chǎng)災(zāi)難。

          const searchObj = {  name: "fatfish",  age: 100,  // ...};const link = `https://medium.com/?name=${searchObj.name}&age=${searchObj.age}`;// https://medium.com/?name=fatfish&age=100

          幸運(yùn)的是,“reduce”可以幫助我們輕松解決這個(gè)問題。

          const stringifySearch = (search = {}) => {  return Object.entries(search)    .reduce(      (t, v) => `${t}${v[0]}=${encodeURIComponent(v[1])}&`,      Object.keys(search).length ? "?" : ""    )    .replace(/&$/, "");};const search = stringifySearch({  name: "fatfish",  age: 100,});const link = `https://medium.com/${search}`;console.log(link); // https://medium.com/?name=fatfish&age=100

          5、展平多層嵌套數(shù)組

          你知道如何展平多層嵌套數(shù)組嗎?

          const array = [1, [2, [3, [4, [5]]]]];// expected output [ 1, 2, 3, 4, 5 ]const flatArray = array.flat(Infinity); // [1, 2, 3, 4, 5]

          “flat”是一個(gè)非常強(qiáng)大的API。

          使用reduce實(shí)現(xiàn)和flat一樣的功能。

          const flat = (array) => {  return array.reduce(    (acc, it) => acc.concat(Array.isArray(it) ? flat(it) : it),    []  );};const array = [1, [2, [3, [4, [5]]]]];const flatArray = flat(array); // [1, 2, 3, 4, 5]

          6、模擬平面特征的功能

          雖然我們已經(jīng)實(shí)現(xiàn)了扁平化深度嵌套數(shù)組的功能,但是如何才能完全實(shí)現(xiàn)扁平化的功能呢?

          // Expand one layer by defaultArray.prototype.flat2 = function (n = 1) {  const len = this.length  let count = 0  let current = this  if (!len || n === 0) {    return current  }  // Confirm whether there are array items in current  const hasArray = () => current.some((it) => Array.isArray(it))  // Expand one layer after each cycle  while (count++ < n && hasArray()) {    current = current.reduce((result, it) => {      result = result.concat(it)      return result    }, [])  }  return current}const array = [ 1, [ 2, [ 3, [ 4, [ 5 ] ] ] ] ]// Expand one layerconsole.log(array.flat()) // [ 1, 2, [ 3, [ 4, [ 5 ] ] ] ] console.log(array.flat2()) // [ 1, 2, [ 3, [ 4, [ 5 ] ] ] ] // Expand allconsole.log(array.flat(Infinity))console.log(array.flat2(Infinity))

          7、保持?jǐn)?shù)組唯一

          reduce 也很容易保持?jǐn)?shù)組的唯一性。

          const array = [ 1, 2, 1, 2, -1, 10, 11 ]const uniqueArray1 = [ ...new Set(array) ]const uniqueArray2 = array.reduce((acc, it) => acc.includes(it) ? acc : [ ...acc, it ], [])

          8、統(tǒng)計(jì)數(shù)組成員的個(gè)數(shù)

          如何計(jì)算數(shù)組中每個(gè)成員的個(gè)數(shù)?

          為什么使用地圖而不是對(duì)象?

          const count = (array) => {  return array.reduce((acc, it) => (acc.set(it, (acc.get(it) || 0) + 1), acc), new Map())}const array = [ 1, 2, 1, 2, -1, 0, '0', 10, '10' ]console.log(count(array))

          9、獲取一個(gè)對(duì)象的多個(gè)屬性

          朋友們,讓我們來看看你在工作中會(huì)遇到的一個(gè)場(chǎng)景。

          // There is an object with many propertiesconst obj = {  a: 1,  b: 2,  c: 3,  d: 4,  e: 5  // ...}// We just want to get some properties above it to create a new objectconst newObj = {  a: obj.a,  b: obj.b,  c: obj.c,  d: obj.d  // ...}// Do you think this is too inefficient?

          使用reduce來解決它

          const getObjectKeys = (obj = {}, keys = []) => {  return Object.keys(obj).reduce((acc, key) => (keys.includes(key) && (acc[key] = obj[key]), acc), {});}const obj = {  a: 1,  b: 2,  c: 3,  d: 4,  e: 5  // ...}const newObj = getObjectKeys(obj, [ 'a', 'b', 'c', 'd' ])console.log(newObj)

          10、反轉(zhuǎn)字符串

          const reverseString = (string) => {  return string.split("").reduceRight((acc, s) => acc + s)}const string = 'fatfish'console.log(reverseString(string)) // hsiftaf

          總結(jié)

          以上就是我今天跟你分享的10個(gè)關(guān)于Reduce的JavaScript技巧,如果你覺得有用的話,請(qǐng)點(diǎn)贊我,關(guān)注我,并將它分享給你的朋友,也許能夠幫助到他。

          最后,感謝你的閱讀,祝編程愉快!


          學(xué)習(xí)更多技能

          請(qǐng)點(diǎn)擊下方公眾號(hào)


          瀏覽 51
          點(diǎn)贊
          評(píng)論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報(bào)
          評(píng)論
          圖片
          表情
          推薦
          點(diǎn)贊
          評(píng)論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報(bào)
          <kbd id="afajh"><form id="afajh"></form></kbd>
          <strong id="afajh"><dl id="afajh"></dl></strong>
            <del id="afajh"><form id="afajh"></form></del>
                1. <th id="afajh"><progress id="afajh"></progress></th>
                  <b id="afajh"><abbr id="afajh"></abbr></b>
                  <th id="afajh"><progress id="afajh"></progress></th>
                  国产精品人人人人 | 一本大道久久久久 | 啪啪视频免费观看 | 一道本无码在线 | 黄色美女大奶被操日韩 |