成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

十個前端開發人員必須知道的關于“[].reduce”的進階技巧

開發 前端
作為一個前端開發者,一定會大量使用reduce函數,它是一個強大而有用的數組API,但是,今天我想給大家分享10個關于它的進階技巧和竅門,加油!

作為一個前端開發者,一定會大量使用reduce函數,它是一個強大而有用的數組API,但是,今天我想給大家分享10個關于它的進階技巧和竅門,加油!

1.作為加法器和累加器

使用“reduce”,我們可以輕松實現多個數相加或累加的功能。

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

2.計算一個數組的最大值和最小值

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

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

我們不得不承認,使用 Math 的 API 是最簡單的方法。

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

2).使用減少

是的,只需一行代碼,你就可以實現與 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).格式化搜索參數

獲取鏈接上的搜索參數是我們經常要處理的事情。如何解析它們?

例如:

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

1).正常方式

這是大多數人使用它的方式。

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

2).使用reduce

Reduce 實際上可以做到這一點,而且看起來更簡單。

const parseQuery = ()  const search = window.location.search;  return search    .replace(/(^\?)|(&$)/g, "")    .split("&")(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.反序列化搜索參數

當我們要跳轉到某個鏈接并為其添加一些搜索參數時,手動拼接的方式不是很方便。

如果要串聯的參數很多,那將是一場災難。

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

幸運的是,“reduce”可以幫助我們輕松解決這個問題。

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. 展平多層嵌套數組

你知道如何展平多層嵌套數組嗎?

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”是一個非常強大的API。而使用reduce可以實現和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.模擬平面特征的功能

雖然,我們已經實現了扁平化深度嵌套數組的功能,但是,如何才能完全實現扁平化的功能呢?

// 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()) {(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. 保持數組唯一

reduce 也很容易保持數組的唯一性。

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.統計數組成員的個數

如何計算數組中每個成員的個數?

為什么使用map而不是boject?

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.獲取一個對象的多個屬性

現在,我們來看看在工作中會遇到的一個場景。

// 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) =>}const obj = {a: 1,b: 2,c: 3,d: 4,e: 5  // ...}const newObj = getObjectKeys(obj, [ 'a', 'b', 'c', 'd' ])console.log(newObj)

10.反轉字符串

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

寫在最后

以上就是我跟你分享的10個關于reduce的知識技巧,希望你你能從中學到一些新的東西,也希望對你有用,如果你覺得有幫助我話,請點贊我,關注我,并將這篇文章與你的開發者朋友一起來分享它。

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

責任編輯:華軒 來源: web前端開發
相關推薦

2022-06-08 10:42:34

ReduceJavaScript技巧

2023-05-11 16:29:39

Javascript開發前端

2018-04-08 10:08:43

開發人員工具

2009-06-25 09:04:22

.NET開發人員

2019-11-25 09:41:28

開發者技能工具

2020-04-20 09:57:00

開發工具技術

2024-11-04 14:18:32

JavaScript編程語言開發

2023-02-27 15:44:17

Java開發技巧

2023-12-12 17:46:33

系統kswapd0內核

2024-10-21 13:15:03

2023-04-11 15:22:06

JavaScript開發前端

2022-03-14 14:11:22

Java開發編程語言

2021-11-06 23:07:47

開發網站編程

2021-11-02 08:54:10

開發編程測試

2023-02-02 08:00:00

SQLJava開發

2017-10-24 11:59:41

JavaScript

2017-12-25 16:15:49

前端JavaScript簡寫技巧

2021-09-15 09:20:37

Python函數代碼

2023-02-26 18:43:05

SQL工具數據庫

2022-12-01 10:05:19

點贊
收藏

51CTO技術棧公眾號

主站蜘蛛池模板: 中文字幕在线不卡播放 | 在线一级片 | 在线观看www | 精品精品 | 亚洲视频三 | 美女福利视频 | 欧美精品一区二区在线观看 | 精品国产乱码久久久久久1区2区 | 在线日韩av电影 | 免费一级欧美在线观看视频 | 国产日韩精品一区二区 | 国产精品久久二区 | 午夜影视免费片在线观看 | 第四色播日韩第一页 | 在线免费看黄 | 99热播精品| 亚洲网站在线观看 | 亚洲国产自产 | 人成在线视频 | 国产色播av在线 | 成人精品国产免费网站 | 久久99精品久久久久久国产越南 | 天天射网站 | 国产欧美一区二区三区在线看 | 欧美亚洲免费 | 91社影院在线观看 | 精品一区二区三区日本 | av网站免费在线观看 | 亚洲淫视频 | 在线中文字幕视频 | 免费久久网站 | 久久九九99 | 亚洲一区久久 | xx性欧美肥妇精品久久久久久 | 日本不卡免费新一二三区 | 草久在线 | 毛片视频免费观看 | 亚洲一区在线免费观看 | 综合久久久久久久 | 热99视频| 91综合在线视频 |