<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>

          JS數(shù)組那些特別好用的技巧

          共 6700字,需瀏覽 14分鐘

           ·

          2020-06-21 23:51


          作者:幻靈爾依

          https://juejin.im/post/5d71fff5f265da03e4678328


          用不好數(shù)組的程序猿不是一個好猿,我說的~

          前段時間接手一個項(xiàng)目,邏輯晦澀難懂,代碼龐大冗余,上手極其困難。很大的原因就是數(shù)組方法使用不熟練,導(dǎo)致寫出了很多垃圾代碼,其實(shí)很多地方稍加改動就可以變得簡單高效又優(yōu)雅。因此我在這里總結(jié)下數(shù)組的常用方法和奇巧淫技(奇巧淫技主要是reduce~)。

          數(shù)組操作首先要注意且牢記splice、sort、reverse這3個常用方法是對數(shù)組自身的操作,會改變數(shù)組自身。其他會改變自身的方法是增刪push/pop/unshift/shift、填充fill和復(fù)制填充copyWithin。

          先說數(shù)組常用方法,后說使用誤區(qū)。

          數(shù)組常用方法

          先獻(xiàn)上數(shù)組方法懶人圖一張祭天?。ǔ?code style="font-size:14px;color:rgb(30,107,184);background-color:rgba(27,31,35,.05);font-family:'Operator Mono', Consolas, Monaco, Menlo, monospace;">Array.keys()/Array.values()/Array.entries()基本都有):

          9b90c0b922285a2e00d09ed5fc8870da.webp數(shù)組方法大全

          生成類似[1-100]這樣的的數(shù)組:

          測試大量數(shù)組數(shù)據(jù)時可以:

          let arr = new Array(100).fill(0).map((item, index) => index + 1)

          數(shù)組解構(gòu)賦值應(yīng)用

          // 交換變量[a, b] = [b, a][o.a, o.b] = [o.b, o.a]// 生成剩余數(shù)組const [a, ...rest] = [...'asdf'] // a:'a',rest: ["s", "d", "f"]

          數(shù)組淺拷貝

          const arr = [1, 2, 3]const arrClone = [...arr]// 對象也可以這樣淺拷貝const obj = { a: 1 }const objClone = { ...obj }

          淺拷貝方法有很多如arr.slice(0, arr.length)/Arror.from(arr)等,但是用了...操作符之后就不會再想用其他的了~

          數(shù)組合并

          const arr1 = [1, 2, 3]const arr2 = [4, 5, 6]const arr3 = [7, 8, 9]const arr = [...arr1, ...arr2, ...arr3]

          arr1.concat(arr2, arr3)同樣可以實(shí)現(xiàn)合并,但是用了...操作符之后就不會再想用其他的了~

          數(shù)組去重

          const arr = [1, 1, 2, 2, 3, 4, 5, 5]const newArr = [...new Set(arr)]

          new Set(arr)接受一個數(shù)組參數(shù)并生成一個set結(jié)構(gòu)的數(shù)據(jù)類型。set數(shù)據(jù)類型的元素不會重復(fù)且是Array Iterator,所以可以利用這個特性來去重。

          數(shù)組取交集

          const a = [0, 1, 2, 3, 4, 5]const b = [3, 4, 5, 6, 7, 8]const duplicatedValues = [...new Set(a)].filter(item => b.includes(item))duplicatedValues // [3, 4, 5]

          數(shù)組取差集

          const a = [0, 1, 2, 3, 4, 5]const b = [3, 4, 5, 6, 7, 8]const diffValues = [...new Set([...a, ...b])].filter(item => !b.includes(item) || !a.includes(item)) // [0, 1, 2, 6, 7, 8]

          數(shù)組轉(zhuǎn)對象

          const arr = [1, 2, 3, 4]const newObj = {...arr} // {0: 1, 1: 2, 2: 3, 3: 4}const obj = {0: 0, 1: 1, 2: 2, length 3}// 對象轉(zhuǎn)數(shù)組不能用展開操作符,因?yàn)檎归_操作符必須用在可迭代對象上let newArr = [...obj] // Uncaught TypeError: object is not iterable...// 可以使用Array.form()將類數(shù)組對象轉(zhuǎn)為數(shù)組let newArr = Array.from(obj) // [0, 1, 2]

          數(shù)組常用遍歷

          數(shù)組常用遍歷有 forEach、every、some、filter、map、reduce、reduceRight、find、findIndex 等方法,很多方法都可以達(dá)到同樣的效果。數(shù)組方法不僅要會用,而且要用好。要用好就要知道什么時候用什么方法。

          遍歷的混合使用

          filtermap方法返回值仍舊是一個數(shù)組,所以可以搭配其他數(shù)組遍歷方法混合使用。注意遍歷越多效率越低~

          const arr = [1, 2, 3, 4, 5]const value = arr    .map(item => item * 3)    .filter(item => item % 2 === 0)    .map(item => item + 1)    .reduce((prev, curr) => prev + curr, 0)

          檢測數(shù)組所有元素是否都符合判斷條件

          const arr = [1, 2, 3, 4, 5]const isAllNum = arr.every(item => typeof item === 'number')

          檢測數(shù)組是否有元素符合判斷條件

          const arr = [1, 2, 3, 4, 5]const hasNum = arr.some(item => typeof item === 'number')

          找到第一個符合條件的元素/下標(biāo)

          const arr = [1, 2, 3, 4, 5]const findItem = arr.find(item => item === 3) // 返回子項(xiàng)const findIndex = arr.findIndex(item => item === 3) // 返回子項(xiàng)的下標(biāo)

          數(shù)組使用誤區(qū)

          數(shù)組的方法很多,很多方法都可以達(dá)到同樣的效果,所以在使用時要根據(jù)需求使用合適的方法。

          垃圾代碼產(chǎn)生的很大原因是數(shù)組常用方法使用不當(dāng),這里有一下需要注意的點(diǎn):

          array.includes() 和 array.indexOf()

          array.includes() 返回布爾值,array.indexOf() 返回?cái)?shù)組子項(xiàng)的索引。indexOf 一定要在需要索引值的情況下使用。

          const arr = [1, 2, 3, 4, 5]
          // 使用indexOf,需要用到索引值const index = arr.indexOf(1) // 0if (~index) { // 若index === -1,~index得到0,判斷不成立;若index不為-1,則~index得到非0,判斷成立。 arr.spilce(index, 1)}
          // 使用includes,不需要用到索引值// 此時若用indexOf會造成上下文上的閱讀負(fù)擔(dān):到底其他地方有沒有用到這個index?const isExist = arr.includes(6) // trueif (!isExist) { arr.push(6)}

          array.find() 、 array.findIndex() 和 array.some()

          array.find()返回值是第一個符合條件的數(shù)組子項(xiàng),array.findIndex() 返回第一個符合條件的數(shù)組子項(xiàng)的下標(biāo),array.some() 返回有無復(fù)合條件的子項(xiàng),如有返回true,若無返回false。注意這三個都是短路操作,即找到符合條件的之后就不在繼續(xù)遍歷。

          在需要數(shù)組的子項(xiàng)的時候使用array.find() ;需要子項(xiàng)的索引值的時候使用 array.findIndex() ;而若只需要知道有無符合條件的子項(xiàng),則用 array.some()。

          const arr = [{label: '男', value: 0}, {label: '女', value: 1}, {label: '不男不女', value: 2}]
          // 使用someconst isExist = arr.some(item => item.value === 2)if (isExist) { console.log('哈哈哈找到了')}
          // 使用findconst item = arr.find(item => item.value === 2)if (item) { console.log(item.label)}
          // 使用findIndexconst index = arr.findIndex(item => item.value === 2)if (~index) { const delItem = arr[index] arr.splice(index, 1) console.log(`你刪除了${delItem.label}`)}

          建議在只需要布爾值的時候和數(shù)組子項(xiàng)是字符串或數(shù)字的時候使用 array.some()

          // 當(dāng)子包含數(shù)字0的時候可能出錯const arr = [0, 1, 2, 3, 4]
          // 正確const isExist = arr.some(item => item === 0)if (isExist) { console.log('存在要找的子項(xiàng),很舒服~')}
          // 錯誤const isExist = arr.find(item => item === 0)if (isExist) { // isExist此時是0,隱式轉(zhuǎn)換為布爾值后是false console.log('執(zhí)行不到這里~')}

          // 當(dāng)子項(xiàng)包含空字符串的時候也可能出錯const arr = ['', 'asdf', 'qwer', '...']
          // 正確const isExist = arr.some(item => item === '')if (isExist) { console.log('存在要找的子項(xiàng),很舒服~')}
          // 錯誤const isExist = arr.find(item => item === '')if (isExist) { // isExist此時是'',隱式轉(zhuǎn)換為布爾值后是false console.log('執(zhí)行不到這里~')}

          array.find() 和 array.filter()

          只需要知道 array.filter() 返回的是所有符合條件的子項(xiàng)組成的數(shù)組,會遍歷所有數(shù)組;而 array.find() 只返回第一個符合條件的子項(xiàng),是短路操作。不再舉例~

          合理使用 Set 數(shù)據(jù)結(jié)構(gòu)

          由于 es6 原生提供了 Set 數(shù)據(jù)結(jié)構(gòu),而 Set 可以保證子項(xiàng)不重復(fù),且和數(shù)組轉(zhuǎn)換十分方便,所以在一些可能會涉及重復(fù)添加的場景下可以直接使用 Set 代替 Array,避免了多個地方重復(fù)判斷是否已經(jīng)存在該子項(xiàng)。

          const set = new Set()set.add(1)set.add(1)set.add(1)set.size // 1const arr = [...set] // arr: [1]

          強(qiáng)大的reduce

          array.reduce 遍歷并將當(dāng)前次回調(diào)函數(shù)的返回值作為下一次回調(diào)函數(shù)執(zhí)行的第一個參數(shù)。

          利用 array.reduce 替代一些需要多次遍歷的場景,可以提高代碼運(yùn)行效率。

          假如有如下每個元素都由字母's'加數(shù)字組成的數(shù)組arr,現(xiàn)在找出其中最大的數(shù)字:(arr不為空)

          const arr = ['s0', 's4', 's1', 's2', 's8', 's3']
          // 方法1 進(jìn)行了多次遍歷,低效const newArr = arr.map(item => item.substring(1)).map(item => Number(item))const maxS = Math.max(...newArr)
          // 方法2 一次遍歷const maxS = arr.reduce((prev, cur) => { const curIndex = Number(cur.replace('s', '')) return curIndex > prev ? curIndex : prev}, 0)
          const arr = [1, 2, 3, 4, 5]
          // 方法1 遍歷了兩次,效率低const value = arr.filter(item => item % 2 === 0).map(item => ({ value: item }))
          // 方法1 一次遍歷,效率高const value = arr.reduce((prev, curr) => { return curr % 2 === 0 ? [...prev, curr] : prev}, [])

          也可用 reduce 做下面這樣的處理來生成想要的 html 結(jié)構(gòu):

          // 后端返回?cái)?shù)據(jù)const data = {  'if _ then s9': [    '作用屬于各種,結(jié)構(gòu)屬于住宅,結(jié)構(gòu)能承受作用,作用屬于在正常建造和正常使用過程中可能發(fā)生',    '作用屬于各種,結(jié)構(gòu)屬于住宅,結(jié)構(gòu)能承受作用,作用屬于在正常建造和正常使用過程中可能發(fā)生',    '作用屬于各種,結(jié)構(gòu)屬于住宅,結(jié)構(gòu)能承受作用,作用屬于在正常建造和正常使用過程中可能發(fā)生'    ],  'if C then s4': [    '當(dāng)有條件時時,結(jié)構(gòu)構(gòu)件滿足要求,要求屬于安全性、適用性和耐久性',    '當(dāng)有條件時時,住宅結(jié)構(gòu)滿足要求,要求屬于安全性、適用性和耐久性'  ]}
          const ifthens = Object.entries(data).reduce((prev, cur) => { const values = cur[1].reduce((prev, cur) => `${prev}

          ${cur}

          `
          , '')
          return ` ${prev}
        2. ${cur[0]}

          ${values}
        3. `}, '')
          const html = `
            ${ifthens}
          `

          生成的 html 結(jié)構(gòu)如下:

          
            
          • if _ then s9

            作用屬于各種,結(jié)構(gòu)屬于住宅,結(jié)構(gòu)能承受作用,作用屬于在正常建造和正常使用過程中可能發(fā)生

            作用屬于各種,結(jié)構(gòu)屬于住宅,結(jié)構(gòu)能承受作用,作用屬于在正常建造和正常使用過程中可能發(fā)生

            作用屬于各種,結(jié)構(gòu)屬于住宅,結(jié)構(gòu)能承受作用,作用屬于在正常建造和正常使用過程中可能發(fā)生

          • if C then s4

            當(dāng)有條件時時,結(jié)構(gòu)構(gòu)件滿足要求,要求屬于安全性、適用性和耐久性

            當(dāng)有條件時時,住宅結(jié)構(gòu)滿足要求,要求屬于安全性、適用性和耐久性

          大招

          哎,流年不利,情場失意。程序界廣大朋友單身的不少,這是我從失敗中總結(jié)出的一點(diǎn)經(jīng)驗(yàn)教訓(xùn),請笑納:

          8f918402c89918f297470f936181c4e1.webp

          支持

          如果你覺得這篇內(nèi)容對你挺有啟發(fā),我想邀請你幫我三個小忙:


          1. 點(diǎn)個「在看」,讓更多的人也能看到這篇內(nèi)容(喜歡不點(diǎn)在看,都是耍流氓 -_-)

          2. 關(guān)注我的官網(wǎng) https://muyiy.cn,讓我們成為長期關(guān)系

          3. 關(guān)注公眾號「高級前端進(jìn)階」,公眾號后臺回復(fù)「面試題」 送你高級前端面試題,回復(fù)「加群」加入面試互助交流群


          》》面試官都在用的題庫,快來看看《《

          瀏覽 53
          點(diǎn)贊
          評論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報
          評論
          圖片
          表情
          推薦
          點(diǎn)贊
          評論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報
          <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>
                  日本黄色A片 | 国产精品乱码69一区二区三区 | 国产超碰免费 | 一级片视频在线观看大全 | 国产熟女AV |