javascript 最全的數組方法總結

第一次在掘金文章,總結一下 js 的數組的一些經常使用的方法,之後開發的時候若是忘了相關方法的語法,看這篇文章就夠啦~~

includesjavascript

該方法用於判斷數組中是否存在某個元素

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

const includeNum4 = arr.includes(4)

const includeNum7 = arr.includes(7)

=> includeNum4 = true  includeNum7 = false
複製代碼

forEach()java

這是最經常使用的用來遍歷數組的方法,須要注意的是該方法不會改變原數組,並且沒有返回值。

const arr = [1,3,4,5,6,8]
arr.forEachI(item => {
  console.log(item)
})
複製代碼

map()react

map() 也是經常使用來遍歷的方法,該方法會返回一個新的數組,但不會改變原數組,默認返回 undefined

const arr = [1,5,3,2,66]
const newArr = arr.map(item => item + 1)

=> newArr = [2,6,4,3,67]

若是沒有顯式跟隱式返回值的話,獲得的數組是全部元素都爲 undefined 的數組

const arr = [1,5,3]
const newArr = arr.map((item, index)=> {console.log(item, index)})

=> newArr = [undefined, undefined, undefined]

在 react 中這也經常使用來遍歷生成 dom 節點,相信都很熟悉

const data = [1,2,3,7]

{
  data.map((item, index) => (
    <div key={index + Math.random()}>{item}</div>
  ))
}

map 遍歷以後儘可能不用 index 做爲返回值,最好用元素的 id 等

複製代碼

find()git

該方法根據檢索條件,找到數組中第一個知足條件的元素,若找不到則返回 undefined

const arr = [1,5,3,22,6]
const bigNum = arr.find(item => item > 6)

=> bigNum = 22
複製代碼

findIndex()github

該方法與 find() 相似根據檢索條件,不一樣的是該方法返回的是索引

const arr = [1,5,3,22,6]
const bigNumIndex = arr.findIndex(item => item > 6)

=> bigNumIndex = 3
複製代碼

filter()算法

該方法顧名思義,這個方法是用來過濾的,該方法返回一個新數組,不改變原數組

const arr = [1,5,3,22,6]
const filterItem = arr.filter(item => item % 2 === 0)

=> filterItem = [22,6]
複製代碼

push() 和 pop()數組

push() 方法在數組末尾添加一個元素,返回數組的長度
const arr = [1,3,5]
const pushArrLen = a.push(7)

=> arr = [1,3,5,7]  pushArrLen = 4

pop() 方法刪除數組最後一個元素並返回該元素
const arr = [1,3,5]
const popArrLen = a.pop()

=> arr = [1,3]  popArrLen = 5

複製代碼

unshift() 和 shift()app

unshift() 方法在數組開頭添加一個元素,返回數組的長度
const arr = [1,3,5]
const unshiftArrLen = arr.unshift(7)

=> arr = [7,1,3,5]  unshiftArrLen = 4

shift() 方法刪除數組第一個元素並返回該元素
const arr = [1,3,5]
const shiftArrLen = a.pop()

=> arr = [3,5]  shiftArrLen = 1

複製代碼

concat() 方法dom

concat() 方法在一個數組後面拼接新的元素,可接收 n 個參數,參數能夠是任意數據類型,若是是數組,則將數組跟原數組拼接,若是是其餘數據類型,則將該元素添加到原數組後面

該方法不改變原數組,會返回拼接好的新數組,所以能夠 執行 鏈式操做

const arr = [1,3,5]

const concatArr = arr.concat(2,4).concat(6,7,8).concat('hello world').concat(() => {}, [9,10,[11,12]])

=> arr = [1,3,5]
   concatArr = [1, 3, 5, 2, 4, 6, 7, 8, 'hello world', () => {}, 9, 10, [11, 12]]



複製代碼

reverse() 方法函數

reverse() 方法將一個數組倒置,該方法返回新的數組,且會改變原數組

const arr = [1, 2, 3, 4]
const reverseArr = arr.reverse()

=> arr = [4, 3, 2, 1]  reverseArr = [4, 3, 2, 1]


複製代碼

sort() 方法

sort() 方法用於將數組排序,能夠接收一個函數做爲參數,當不傳遞參數時,sort 將按照內部定義的生序的規則進行排序,該方法返回排序後的數組,原數組將被改變。

const arr = [[() => {}], [12], '4', [11], 123, 'hello', n => n + 1, () => {}, 1, []]

const sortArr = a.sort()

sortArr = [[], () => {}, [() => {}], 1, [11], [12], 123, '4', n => n + 1, 'hello']

默認的排序算法是調用每一個數組項的 toString() 轉型方法,比較獲得的字符串的編碼大小,按照最小值在前面,最大值在後面的方式排序。也就是正序,與 

sortArr = arr.sort((c, d) => c - d)

等價,倒序爲

sortArr = arr.sort((c, d) => d - c)

舉例:

const arr = [
  { id: 4, name: 'michael' },
  { id: 2, name: 'kangkang' },
  { id: 3, name: 'meria' },
  { id: 1, name: 'jane' },
]

const newArr = arr.sort((a, b) => b.id - a.id)

=>
newArr = [
  { id: 4, name: 'michael' },
  { id: 3, name: 'meria' },
  { id: 2, name: 'kangkang' },
  { id: 1, name: 'jane' }
]


複製代碼

join() 和 split()

join() 方法將數組的元素組起一個字符串,以separator爲分隔符,省略的話則用默認用逗號爲分隔符,該方法只接收一個參數:即分隔符,該方法返回拼接後的字符串,不改變原數組。

const arr = [1, 3, 'hello']

const newArr = arr.join('-')

=>  newArr = '1-3-hello'

經過join()方法能夠實現重複字符串,只需傳入字符串以及重複的次數,就能返回重複後的字符串

const repeatStr = (str, n) => new Array(n).join(str)

const newStr = repeatStr('hi', 3)

=>  newStr = 'hihihi'


split() 方法將一個字符串分割爲數組,接收一個參數,以該參數爲分割符

const str = 'charming javascript'

const strArr1 = str.split('')
const strArr2 = str.split('j')
      
=>  strArr1 = ["c", "h", "a", "r", "m", "i", "n", "g", " ", "j", "a", "v", "a", "s", "c", "r", "i", "p", "t"]
    strArr2 = ['charming ', 'avascript']


複製代碼

every() 和 some()

every() 方法接收一個函數做爲參數,判斷數組中每一項都是否知足條件,只有全部項都知足條件,纔會返回trueconst arr = [1,5,2,4,11]

const isBig = arr.every(item => item > 5)
const isSmall = arr.every(item => item < 20)

=> isBig = true  isSmall = false


some() 方法接收一個函數做爲參數,數組中只要有一項知足條件,則返回 true,若是都不知足條件,則返回 false

const arr = [
	{ price: 10, name: 'apple' },
	{ price: 20, name: 'orange' },
	{ price: 15, name: 'banana' }
]

const isCheap = arr.some(item => item.price < 15)

const isExpensive = arr.some(item => item.price > 20)

=> isCheap = true  isExpensive = false


複製代碼

indexOf() 和 lastIndexOf()

兩個方法都用來查找索引,接收兩個參數,第一個參數是要查找的元素,第二個參數是查找的起始位置(默認第一項和最後一項的位置)。都會返回該元素的正索引,不一樣的是當有第二個參數時,indexOf() 只查找該元素以後的元素,lastIndexOf() 只查找該元素以前的元素。若找到該元素則返回索引,若找不到則返回 -1

const arr = [1, 3, 5, 7, 9]

const index = arr.indexOf(7, 0)
const lastIndex = arr.lastIndexOf(7, 2)

=> index = 3  lastIndex = -1


複製代碼

slice()

slice(start, end) 接收兩個參數,start < end,返回 [start, end) 區間之間的元素數組,不改變原數組

const arr = [1, 2, 3, 4, 5, 6, 7, 8]

const sliceArr = arr.slice(3, 5)

=>  sliceArr = [4, 5]

並且 slice() 能夠接收負數做爲參數, -1 爲倒數第一個元素,-2 爲倒數第二個元素,依此類推


複製代碼

splice()

splice() 方法向/從數組中添加/刪除項目,而後返回被刪除的項目。該方法會改變原始數組。

splice(index, howmany, item1, item2...itemx)

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

const spliceArr = arr.splice(2, 3, 6, 7, 8)

=> arr = [1, 2, 6, 7, 8]  spliceArr = [3, 4, 5]


複製代碼

reduce()

reduce() 方法...額,它能夠搞定的東西...咱們一一舉例

語法:	arr.reduce(callback, initialValue)

reduce 爲數組中的每個元素依次執行回調函數,不包括數組中被刪除或從未被賦值的元素,接受四個參數:初始值(或者上一次回調函數的返回值),當前元素值,當前索引,調用 reduce 的數組。也就是:

arr.reduce((prev, current, index, array) => {}, initialValue)

下面看一些 reduce 的應用

數組求和:
const arr = [1,2,3,4,5]
const sum = arr.reduce((prev, current) => prev + current, 0)		=> sum = 15

數組求積:
const arr = [1,2,3,4,5]
const pow = arr.reduce((prev, current) => prev * current, 1)		=>  pow = 120

數組去重:
const arr = [1,3,4,2,5,3,4]
const slimArr = arr.reduce((prev, current) => {
  if(prev.includes(current)) {
    return prev
  } else {
    return prev.concat(current)
  }
}, [])

求字符串的字節長度:
const str = 'charming javascript'
const byteLen = str.split('').map(item => item.charCodeAt() > 255 ? 2 : 1).reduce((prev, current) => prev + current, 0)

求對象裏的數乘積再求和:
const fruitArr = [
 { name: 'apple', price: 10, quantity: 2 },
 { name: 'orange', price: 15, quantity: 4 },
 { name: 'banana', price: 5, quantity: 3 },
]
const totalPrice = fruitArr.reduce((prev, current) => {
 return prev + current.price * current.quantity
}, 0)


複製代碼

github 求個 star,會陸續更新

數組方法總結

相關文章
相關標籤/搜索