JS數組奇巧淫技

用很差數組的程序猿不是一個好猿,我說的~html

前段時間接手一個項目,邏輯晦澀難懂,代碼龐大冗餘,上手極其困難。很大的緣由就是數組方法使用不熟練,致使寫出了不少垃圾代碼,其實不少地方稍加改動就能夠變得簡單高效又優雅。所以我在這裏總結下數組的經常使用方法和奇巧淫技(奇巧淫技主要是reduce~)。es6

數組操做首先要注意且牢記splice、sort、reverse這3個經常使用方法是對數組自身的操做,會改變數組自身。其餘會改變自身的方法是增刪push/pop/unshift/shift、填充fill和複製填充copyWithin後端

先說數組經常使用方法,後說使用誤區。數組

數組經常使用方法

先獻上數組方法懶人圖一張祭天 (除了Array.keys()/Array.values()/Array.entries()基本都有):安全

數組方法大全

生成相似[1-100]這樣的的數組:

測試大量數據的數組時能夠這樣生成:數據結構

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

// Array.from() 評論區大佬指出
const arr = Array.from(Array(100), (v, k) => k + 1)

// Array.from() + array.keys() 評論區大佬指出
const ary = [...Array(100).keys()] 
複製代碼

new Array(100) 會生成一個有100空位的數組,這個數組是不能被map(),forEach(), filter(), reduce(), every() ,some()遍歷的,由於空位會被跳過(for of不會跳過空位,能夠遍歷)。 [...new Array(4)] 能夠給空位設置默認值undefined,從而使數組能夠被以上方法遍歷。函數

數組解構賦值應用

// 交換變量
[a, b] = [b, a]
[o.a, o.b] = [o.b, o.a]
// 生成剩餘數組
const [a, ...rest] = [...'asdf'] // a:'a',rest: ["s", "d", "f"]
複製代碼

數組淺拷貝

const arr = [1, 2, 3]
const arrClone = [...arr]
// 對象也能夠這樣淺拷貝
const obj = { a: 1 }
const objClone = { ...obj }
複製代碼

淺拷貝方法有不少如arr.slice(0, arr.length)/Arror.from(arr)等,可是用了...操做符以後就不會再想用其餘的了~post

數組合並

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

arr1.concat(arr2, arr3)一樣能夠實現合併,可是用了...操做符以後就不會再想用其餘的了~測試

數組去重

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

new Set(arr)接受一個數組參數並生成一個set結構的數據類型。set數據類型的元素不會重複且是Array Iterator,因此能夠利用這個特性來去重。ui

數組取交集

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]
複製代碼

數組取差集

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]
複製代碼

數組轉對象

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}
// 對象轉數組不能用展開操做符,由於展開操做符必須用在可迭代對象上
let newArr = [...obj] // Uncaught TypeError: object is not iterable...
// 可使用Array.form()將類數組對象轉爲數組
let newArr = Array.from(obj) // [0, 1, 2]
複製代碼

數組攤平

const obj = {a: '羣主', b: '男羣友', c: '女裙友', d: '未知性別'}
const getName = function (item) { return item.includes('羣')}
// 方法1
const flatArr = Object.values(obj).flat().filter(item => getName(item))
// 經大佬指點,更加簡化(發現本身的抽象能力真的差~)
const flatArr = Object.values(obj).flat().filter(getName)
複製代碼

二維數組用array.flat(),三維及以上用array.flatMap()

數組經常使用遍歷

數組經常使用遍歷有 forEach、every、some、filter、map、reduce、reduceRight、find、findIndex 等方法,不少方法均可以達到一樣的效果。數組方法不只要會用,並且要用好。要用好就要知道何時用什麼方法。

遍歷的混合使用

filtermap方法返回值仍舊是一個數組,因此能夠搭配其餘數組遍歷方法混合使用。注意遍歷越多效率越低~

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)
複製代碼

檢測數組全部元素是否都符合判斷條件

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

檢測數組是否有元素符合判斷條件

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

找到第一個符合條件的元素/下標

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

// 我之後不再想看見下面這樣的代碼了😂
let findIndex
arr.find((item, index) => {
    if (item === 3) {
        findIndex = index
    }
})
複製代碼

數組使用誤區

數組的方法不少,不少方法均可以達到一樣的效果,因此在使用時要根據需求使用合適的方法。

垃圾代碼產生的很大緣由就是數組經常使用方法使用不當,這裏有如下須要注意的點:

array.includes() 和 array.indexOf()

array.includes() 返回布爾值,array.indexOf() 返回數組子項的索引。indexOf 必定要在須要索引值的狀況下使用。

const arr = [1, 2, 3, 4, 5]

// 使用indexOf,須要用到索引值
const index = arr.indexOf(1) // 0
if (~index) { // 若index === -1,~index獲得0,判斷不成立;若index不爲-1,則~index獲得非0,判斷成立。
    arr.spilce(index, 1)
}

// 使用includes,不須要用到索引值
// 此時若用indexOf會形成上下文上的閱讀負擔:到底其餘地方有沒有用到這個index?
const isExist = arr.includes(6) // true
if (!isExist) {
    arr.push(6)
}
複製代碼

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

array.find()返回值是第一個符合條件的數組子項,array.findIndex() 返回第一個符合條件的數組子項的下標,array.some() 返回有無複合條件的子項,若有返回true,若無返回false。注意這三個都是短路操做,即找到符合條件的以後就不在繼續遍歷。

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

const arr = [{label: '男', value: 0}, {label: '女', value: 1}, {label: '不男不女', value: 2}]

// 使用some
const isExist = arr.some(item => item.value === 2)
if (isExist) {
    console.log('哈哈哈找到了')
}

// 使用find
const item = arr.find(item => item.value === 2)
if (item) {
    console.log(item.label)
}

// 使用findIndex
const index = arr.findIndex(item => item.value === 2)
if (~index) {
    const delItem = arr[index]
    arr.splice(index, 1)
    console.log(`你刪除了${delItem.label}`)
}
複製代碼

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

// 當子包含數字0的時候可能出錯
const arr = [0, 1, 2, 3, 4]

// 正確
const isExist = arr.some(item => item === 0)
if (isExist) {
    console.log('存在要找的子項,很舒服~')
}

// 錯誤
const isExist = arr.find(item => item === 0)
if (isExist) { // isExist此時是0,隱式轉換爲布爾值後是false
    console.log('執行不到這裏~')
}


// 當子項包含空字符串的時候也可能出錯
const arr = ['', 'asdf', 'qwer', '...']

// 正確
const isExist = arr.some(item => item === '')
if (isExist) {
    console.log('存在要找的子項,很舒服~')
}

// 錯誤
const isExist = arr.find(item => item === '')
if (isExist) { // isExist此時是'',隱式轉換爲布爾值後是false
    console.log('執行不到這裏~')
}
複製代碼

array.find() 和 array.filter()

只須要知道 array.filter() 返回的是全部符合條件的子項組成的數組,會遍歷全部數組;而 array.find() 只返回第一個符合條件的子項,是短路操做。再也不舉例~

合理使用 Set 數據結構

因爲 es6 原生提供了 Set 數據結構,而 Set 能夠保證子項不重複,且和數組轉換十分方便,因此在一些可能會涉及重複添加的場景下能夠直接使用 Set 代替 Array,避免了多個地方重複判斷是否已經存在該子項。

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

強大的reduce(奇巧淫技)

array.reduce 遍歷並將當前次回調函數的返回值做爲下一次回調函數執行的第一個參數。

利用 array.reduce 替代一些須要屢次遍歷的場景,能夠極大提升代碼運行效率。

  1. 利用reduce 輸出一個數字/字符串

假若有以下每一個元素都由字母's'加數字組成的數組arr,如今找出其中最大的數字:(arr不爲空)

const arr = ['s0', 's4', 's1', 's2', 's8', 's3']

// 方法1 進行了屢次遍歷,低效
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)
複製代碼
  1. 利用reduce 輸出一個數組/對象
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/reduceRight 實現各類奇巧淫技了。

實例:利用 reduce 作下面這樣的處理來生成想要的 html 字符串:

// 後端返回數據
const data = {
  'if _ then s9': [
    '做用屬於各類,結構屬於住宅,結構能承受做用,做用屬於在正常建造和正常使用過程當中可能發生',
    '做用屬於各類,結構屬於住宅,結構能承受做用,做用屬於在正常建造和正常使用過程當中可能發生',
    '做用屬於各類,結構屬於住宅,結構能承受做用,做用屬於在正常建造和正常使用過程當中可能發生'
    ],
  'if C then s4': [
    '當有條件時時,結構構件知足要求,要求屬於安全性、適用性和耐久性',
    '當有條件時時,住宅結構知足要求,要求屬於安全性、適用性和耐久性'
  ]
}

const ifthens = Object.entries(data).reduce((prev, cur) => {
  const values = cur[1].reduce((prev, cur) => `${prev}<p>${cur}</p>`, '')
  return ` ${prev} <li> <p>${cur[0]}</p> ${values} </li> `
}, '')

const html = ` <ul class="nlp-notify-body"> ${ifthens} </ul> `
複製代碼

生成的 html 結構以下:

<ul class="nlp-notify-body">            
  <li>
    <p>if _ then s9</p>
    <p>做用屬於各類,結構屬於住宅,結構能承受做用,做用屬於在正常建造和正常使用過程當中可能發生</p>
    <p>做用屬於各類,結構屬於住宅,結構能承受做用,做用屬於在正常建造和正常使用過程當中可能發生</p>
    <p>做用屬於各類,結構屬於住宅,結構能承受做用,做用屬於在正常建造和正常使用過程當中可能發生</p>
  </li>
  <li>
    <p>if C then s4</p>
    <p>當有條件時時,結構構件知足要求,要求屬於安全性、適用性和耐久性</p>
    <p>當有條件時時,住宅結構知足要求,要求屬於安全性、適用性和耐久性</p>
  </li>
</ul>
複製代碼

這裏還有一個替代 reverse 函數的技巧

因爲 array.reverse() 函數會改變原數組自身,這樣就限制了一些使用場景。若是我想要一個不會改變數組自身的 reverse 函數呢?拿走!

const myReverse = (arr = []) => {
    return  arr.reduceRight((prev, cur) => [...prev, cur], []) // 也能夠返回逗號表達式 (prev.push(cur), prev)
}
複製代碼

reduce 太強大了,這裏只能展現基本用法。到底有多強大推薦查看大佬這篇《25個你不得不知道的數組reduce高級用法》

大招

哎,流年不利,情場失意。程序界廣大朋友中單身的很多,這是我從失敗中總結出的一點經驗教訓,請笑納😂~

相關文章
相關標籤/搜索
本站公眾號
   歡迎關注本站公眾號,獲取更多信息