全面介紹JavaScript數組方法

隨着JavaScript的發展,JavaScriptArray也增長了許多方法。有必要全面瞭解一下。本文基本涵蓋了Array全部的方法介紹。javascript

1、 檢測方法

Array.isArray()

判斷傳入的值是不是一個數組。java

// true
Array.isArray([1, 2, 3])
// false
Array.isArray({foo: 123})
// false
Array.isArray('foobar')   
// false
Array.isArray(undefined)  
複製代碼

2、 建立數組方法

Array.from()

Array.from()方法用於將類數組對象可迭代對象轉爲真正的數組,而且返回一個新的,淺拷貝的數組實例。es6

// 報錯
Array.from(undefined)
// 報錯
Array.from(null)
// ["f", "o", "o"]
console.log(Array.from('foo'))
// []
console.log(Array.from(''))
// []
console.log(Array.from(123))
// []
console.log(Array.from(NaN))

// arguments對象轉爲數組
function foo() {
  const args = Array.from(arguments)
  //true
  console.log(Array.isArray(args))
}
foo(1, 2, 3)

// NodeList對象轉爲數組
Array.from(document.querySelectorAll('p'))

// Set對象轉爲數組:['a','b']
Array.from(new Set(['a', 'b'])) 

// Map對象轉爲數組:[[1, 2], [2, 4]]
Array.from(new Map([[1, 2], [2, 4]])) 
複製代碼

Array.from()能夠傳入3個參數:數組

  1. 第一個參數(必填):想要轉換成數組的類數組對象或可迭代對象。
  2. 第二個參數(可選):數組中的每一個元素會執行該回調函數。
  3. 第三個參數(可選):執行第二個參數回調函數時須要綁定的this對象。
// 傳入第二個參數回調函數:[2, 4, 6]
Array.from([1, 2, 3], x => x + x)
複製代碼
let obj = {
  num: 1,
  handle: function(value){
    return n + this.num
  }
}
// 傳入第三個參數修改this指向:[2, 3, 4, 5, 6]
const arrs = Array.from([1, 2, 3, 4, 5], obj.handle, obj)
複製代碼
// 獲得數組對象裏的id屬性:[1, 2]
const obj = [{id: 1,name: 'zhangsan'},{id: 2,name: 'lisi'}]
Array.from(obj,(el) => {
  return el.id
})
複製代碼

注意: Array.from(null)或者Array.from(undefined)會拋出異常bash

Array.of()

Array.of()建立一個包含全部傳入參數的數組,不考慮參數的數量或類型,返回一個新數組。ide

使用Array.of()建立新數組:函數

Array.of()                  // []
Array.of(undefined)         // [undefined]
Array.of(null)              // [null]
Array.of(NaN)               // [NaN]
Array.of(1)                 // [1]
Array.of(1, 2)              // [1, 2]
Array.of([1,2,3])           // [[1,2,3]]
Array.of({id: 1},{id: 2})   // [{id:1}, {id:2}]
複製代碼

3、 遍歷(迭代)方法

forEach()

對數組中的每一項運行指定的函數。這個方法返回undefined,即便你return了一個值。post

Array.forEach()參數語法:測試

  1. 第一個參數(必填): callback在數組每一項上執行的函數。該函數接收三個參數:
element index array
當前元素 當前元素的索引 (可選) 數組自己(可選)
  1. 第二個參數(可選):當執行回調函數時用做 this 的值。
const arr = [{id: 1,name: 'zhangsan'},{id: 2,name: 'lisi'}]
// 1 - zhangsan
// 2 - lisi
arr.forEach(el => {
    console.log(`${el.id} - ${el.name}`);
});

const obj = {
  handle: function(n){
    return n + 2
  }
};
// true 
[{id: 1,name: 'zhangsan'},{id: 2,name: 'lisi'}].forEach(function(el,index,arr){
  if(el.id === 1) {
    return
  }
  console.log(this === obj)
},obj);
複製代碼

Array.forEach()不能中斷循環(使用break,或continue語句)。只能用return退出本次回調,進行下一次回調。ui

map()

返回一個新數組,結果是該數組中的每一個元素都調用提供的函數後返回的結果。

Array.map()參數語法:

  1. 第一個參數(必填): callback生成新數組元素的函數。該函數接收三個參數:
element index array
當前元素 當前元素的索引 (可選) 數組自己(可選)
  1. 第二個參數(可選):當執行回調函數時用做 this 的值。
const arr = [{id: 1},{id: 2},{id: 3}]
const newArr = arr.map((el,index,arr) => {
  el.age = 20
  return el
});
//[{id: 1,age: 20},{id: 2,age: 20},{id: 3,age: 20}]
console.log(newArr);
複製代碼

filter()

對數組中的每一項運行指定的函數,返回該函數會返回true的項組成的新的數組。若是沒有任何數組元素經過測試,則返回空數組。

Array.filter()參數語法:

  1. 第一個參數(必填): callback用來測試數組的每一個元素的函數。返回true 表示該元素經過測試,保留該元素,false 則不保留。該函數接收三個參數:
element index array
當前元素 當前元素的索引 (可選) 數組自己(可選)
  1. 第二個參數(可選):當執行回調函數時用做 this 的值。
const arr = [{id: 1},{id: 2},{id: 3}]
const newArr = arr.map((el,index,arr) => {
  el.age = 20
  return el
});
// [{id: 1,age: 20},{id: 2,age: 20},{id: 3,age: 20}]
console.log(newArr);
複製代碼

some()

檢測數組中的是否有知足判斷條件的元素。

對數組中的每一項運行指定的函數,若是該函數對任一項返回true,則返回true,而且剩餘的元素不會再執行檢測。若是沒有知足條件的元素,則返回false

Array.some()參數語法:

  1. 第一個參數(必填): callback用來測試每一個元素的函數。該函數接收三個參數:
element index array
當前元素 當前元素的索引 (可選) 數組自己(可選)
  1. 第二個參數(可選):當執行回調函數時用做 this 的值。
const arr = [{id: 1},{id: 2},{id: 3}]
const someResult = arr.some((el,index,arr) => {
  return el.id === 1
});
// true
console.log(someResult)
複製代碼

every()

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

對數組中的每一項運行指定的函數,若是該函數對每一項都返回true,則返回true。若收到一個空數組,此方法在一切狀況下都會返回true。若是數組中檢測到有一個元素不知足,則返回 false,且剩餘的元素不會再進行檢測。

Array.every()參數語法:

  1. 第一個參數(必填): callback用來測試每一個元素的函數。該函數接收三個參數:
element index array
當前元素 當前元素的索引 (可選) 數組自己(可選)
  1. 第二個參數(可選):當執行回調函數時用做 this 的值。
// true
[].every(() => {})
複製代碼
const arr = [{id: 1},{id: 2},{id: 3}]
const everyResult = arr.every((el,index,arr) => {
  return el.id > 0
});
// true
console.log(everyResult)
複製代碼

find()

返回數組中匹配的第一個元素的值,不然返回undefined

Array.find()參數語法:

  1. 第一個參數(必填): callback在數組每一項上執行的函數。該函數接收三個參數:
element index array
當前元素 當前元素的索引 (可選) 數組自己 (可選)
  1. 第二個參數(可選):當執行回調函數時 this 的值。
const arr = [{id: 1},{id: 2},{id: 3}]
const findResult = arr.find((el,index,arr) => {
  return el.id  === 1
},obj);
// {id: 1}
console.log(findResult)
複製代碼

findIndex()

返回數組中匹配的第一個元素的索引。不然返回-1

Array.findIndex()參數語法:

  1. 第一個參數(必填): callback在數組每一項上執行的函數。該函數接收三個參數:
element index array
當前元素 當前元素的索引值 數組自己
  1. 第二個參數(可選):當執行回調函數時 this 的值。
const arr = [{id: 1},{id: 2},{id: 3}]
// 2
const findResult = arr.findIndex((el,index,arr) => {
  return el.id  === 3
},obj)
複製代碼

entries()keys()values()

用於遍歷數組,它們都返回一個遍歷器Array Iterator對象。能夠用for...of循環進行遍歷,他們的區別是keys()是對鍵名的遍歷、values()v是對鍵值的遍歷,entries()`是鍵值對的遍歷。

// 0
// 1
for (let i of ['a', 'b'].keys()) {
  console.log(i)
}

// a
// b
for (let el of ['a', 'b'].values()) {
  console.log(el)
}

// 0-a
// 1-b
for (let [i, el] of ['a', 'b'].entries()) {
  console.log(`${i}-${el}`)
}
複製代碼

能夠手動調用遍歷器對象的next方法,進行遍歷。

const arr = ['a', 'b', 'c']
const tempIterator = arr.entries()
// [0, "a"]
console.log(tempIterator.next().value)

// [1, "b"]
console.log(tempIterator.next().value)
複製代碼

4、操做方法

push()

將一個或多個元素添加到數組的末尾,並返回該數組的新長度。

var numbers = [1, 2, 3]
// 5
console.log(numbers.push(4,5))
// [1,2,3,4,5]
console.log(numbers)
複製代碼

pop()

從數組中刪除最後一個元素,並返回刪除的元素。

const arr = ['a', 'b', 'c']
// c
console.log(arr.pop())
// ["a", "b"]
console.log(arr);
複製代碼

shift()

shift() 方法從數組中刪除第一個元素,並返回刪除的元素。

const arr = ['a', 'b', 'c']
// a
console.log(arr.shift())
// ["b", "c"]
console.log(arr)
複製代碼

unshift()

將一個或多個元素添加到數組的開頭,並返回該數組的新長度(該方法修改原有數組)。

const arr = ['a', 'b', 'c']
// 5
console.log(arr.unshift('d', 'e'))
// ["d", "e", "a", "b", "c"]
console.log(arr)
複製代碼

concat()

用於合併兩個或多個數組。此方法不會更改現有數組,而是返回一個新數組。若是省略參數,則concat會返回當前數組的淺拷貝。

const arr = [1, 2, 3]
const newArr = arr.concat()
// [1,2,3]
console.log(newArr)
// false
console.log(newArr === arr)
複製代碼
const arr = [1, 2, 3]
const newArr = arr.concat([4, 5])
// [1, 2, 3, 4, 5]
console.log(newArr)
複製代碼

indexOf()lastIndexOf()

這兩個方法都返回要查找的元素在數組中的位置,或者在沒找到的狀況下返回-1indexOf()方法從數組的開頭開始向後查找,lastIndexOf()方法則從數組的末尾開始向前查找。

Array.indexOf()、Array.lastIndexOf()參數語法:

  1. 第一個參數 searchElement(可選):被查找的元素。
  2. 第二個參數 fromIndex(可選):indexOf()方法表示開始向後查找的位置。默認值爲0lastIndexOf()方法表示今後位置開始逆向查找。默認爲數組的長度減 1 (arr.length - 1)。

indexOf()

const numbers = [1, 2, 3, 4, 5, 4]
// 3
console.log(numbers.indexOf(4))
// 5
console.log(numbers.indexOf(4, 4)) 
複製代碼

lastIndexOf()

const numbers = [1, 2, 3, 4, 5, 4]
// 5
console.log(numbers.lastIndexOf(4))
// 3
console.log(numbers.lastIndexOf(4, 4))
複製代碼

slice()

建立一個新的數組並返回。該方法接受兩個參數:是一個由起始索引和結束索引的提取出來的原數組的淺拷貝。原始數組不會被改變。

Array.slice()參數語法:

  1. 第一個參數(可選):起始索引 begin(默認從 0 開始),從該索引開始提取原數組元素。
  2. 第二個參數(可選):結束索引 end 在該索引結束提取原數組元素。若是該參數省略,則一直提取到原數組末尾結束。slice 會提取原數組中beginend的全部元素(包含 begin,但不包含end)。
const arr = [1, 2, 3, 4]
const newArr = arr.slice(1)
// [2,3,4]
console.log(newArr);
const newArr1 = arr.slice(1, 3)
// [2,3]
console.log(newArr1)
複製代碼

若是結束位置小於起始位置,則返回空數組。

const arr = [1, 2, 3, 4]
const newArr = arr.slice(2, 1)
// []
console.log(newArr)
複製代碼

splice()

向數組的中刪除插入替換元素。返回值是被刪除的元素組成的一個數組。若是沒有刪除元素,則返回空數組。此方法會改變原數組。

刪除任意數量的元素,傳入 2 個參數,要刪除的元素開始索引和要刪除的個數。

const arr = [{ id: 1 }, { id: 2 }, { id: 3 }]
//刪除前兩個元素
arr.splice(0, 2)
// [{id: 3}]
console.log(arr)
複製代碼

向指定位置插入任意數量的元素,傳入3個參數:起始位置、0(要刪除的元素個數) 和要插入的元素。若是要插入多個元素,能夠再傳入第4、第五,以致任意多個元素。

const arr = [{ id: 1 }, { id: 2 }, { id: 3 }]
// 從索引 1 開始插入兩個元素
arr.splice(1, 0, { id: 4 }, { id: 5 })
// [{ id: 1 }, { id: 4 }, { id: 5 },{ id: 2 }, { id: 3 }]
console.log(arr)
複製代碼

向指定位置插入任意數量的元素,且同時刪除任意數量的元素。傳入3個參數:起始位置、要刪除的元素個數和要插入的元素。

const arr = [{ id: 1 }, { id: 2 }, { id: 3 }]
// 從索引 1 開始,刪除一個元素,並切插入兩個元素
arr.splice(1, 1, { id: 4 }, { id: 5 })
// [{ id: 1 }, { id: 4 }, { id: 5 },{ id: 3 }]
console.log(arr)
複製代碼

copyWithin()

在數組內部替換自身元素,返回修改後的當前數組。

Array.copyWithin()參數語法:

  1. 第一個參數(必填):從該位置開始替換元素。
  2. 第二個參數(可選):從該位置開始複製數據,默認爲 0
  3. 第三個參數(可選):中止複製的索引(不包含自身),默認值爲數組的長度。
// 將數組的前兩個元素替換數組的最後兩個位置:[1,2,1,2]
// 從索引2的位置開始替換
// 從索引0的位置開始複製數據
[1, 2, 3, 4].copyWithin(2,0)

const arr = [{id: 1},{id: 2},{id: 3}]
// [{id: 3},{id: 2},{id: 3}]
arr.copyWithin(0, 2)

// 從索引2的位置開始替換
// 從索引0的位置開始複製
// 在遇到索引1的時候中止複製(不包含自身)
// [1,2,1,4]
[1, 2, 3, 4].copyWithin(2,0)
複製代碼

fill()

使用固定值填充一個數組中一個或多個元素。

  1. 第一個參數:用來填充數組元素的值。
  2. 第二個參數(可選):起始索引,默認值爲0
  3. 第二個參數(可選):終止索引,默認值爲數組的長度。

當傳入一個參數的時候,會用這個參數的值填充整個數組:

const arr = [{ id: 1 }, { id: 2 }, { id: 3 }]

arr.fill({ id: 4 })
// [{ id: 4 }, { id: 4 }, { id: 4 }]
console.log(arr)
// true
console.log(arr[0] === arr[1])
複製代碼

當傳入多個個參數的時候,用這個參數的值填充部分數組:

const arr = [{ id: 1 }, { id: 2 }, { id: 3 }]
// 從數組下標索引爲1的元素開始填充
arr.fill({ id: 4 }, 1)
// [{ id: 1 }, { id: 4 }, { id: 4 }]
console.log(arr)

// 填充的元素不包括終止的索引元素。
const numbers = [1, 2, 3, 4]
numbers.fill(0, 1, 2)
// [1, 0, 3, 4]
console.log(numbers)
複製代碼

flat()

將嵌套的數組,變成一維的數組。返回一個新數組。

Array.flat()參數語法:

  1. 第一個參數(可選):指定要提取嵌套數組的結構深度,默認值爲 1。

展開一層

const arr = [1, 2, [3, 4]]
const newArr = arr.flat()
//[1,2,3,4]
console.log(newArr)
複製代碼

展開兩層

const arr = [1, 2, [3, [4, 5]]]
const newArr = arr.flat()
// [1, 2, 3, 4, 5]
console.log(newArr)
複製代碼

使用 Infinity,可展開任意深度的嵌套數組

var arr = [1, 2, [3, 4, [5, 6, [7, 8, [9, 10]]]]];
const newArr = arr.flat(Infinity)
// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
console.log(newArr)
複製代碼

移除數組中的空項

var arr = [1, 2, , 4, 5]
const newArr = arr.flat()
// [1, 2, 4, 5]
console.log(newArr)
複製代碼

flatMap()

對原數組的每一個成員執行一個函數,而後對返回值組成的數組執行flat()方法。該方法返回一個新數組,不改變原數組。

Array.flatMap()參數語法:

  1. 第一個參數(必填): callback遍歷函數。該函數接收三個參數:
element index array
當前元素 當前元素的索引(可選) 數組對象自己(可選)
  1. 第二個參數(可選):當執行回調函數時this的值。
var arr = [1, 2]
const newArr = arr.flatMap(el => [el, el * 2])
[1,2,2,4]
console.log(newArr)
複製代碼

flatMap()只能展開一層數組

var arr = [1, 2]
const newArr = arr.flatMap(el => [[el, el * 2]])
// [[1,2],[2,4]]
console.log(newArr)
複製代碼

includes()

判斷一個數組是否包含一個指定的值,若是包含則返回true,不然返回false。使用 includes()比較字符串和字符時是區分大小寫的。

Array.includes()參數語法:

  1. 第一個參數:須要查找的元素值。

  2. 第二個參數:表示搜索的起始位置,默認爲0

const obj = { id: 1 }
var arr = [obj, { id: 2 }]
// true
console.log(arr.includes(obj))
複製代碼

傳入第二個參數

console.log([1, 2, 3].includes(3));    // true
console.log([1, 2, 3].includes(3, 3))  // false
console.log([1, 2, 3].includes(3, 2))  // true
複製代碼

5、排序方法

sort()

對數組的元素進行排序,並返回排序後的原數組。

Array.sort()參數語法:

  1. 第一個參數(可選):用來指定按某種順序進行排列的函數。若是省略,元素按照轉換爲的字符串的各個字符串的ASCII碼進行排序。該函數接收二個參數:
first second
第一個用於比較的元素 第二個用於比較的元素
// Array的sort()方法默認把全部元素先轉換爲String再排序,結果'10'排在了'2'的前面,由於字符'1'比字符'2'的ASCII碼小。
const arr = [10, 20, 1, 2].sort()
//[1, 10, 2, 20]
console.log(arr);
複製代碼

能夠接收一個比較函數做爲參數,實現自定義的排序。該函數接收兩個參數,若是第一個參數應該位於第二個以前則返回一個負數,若是兩個參數相等返回0,若是第一個參數應該位於第二個以後則返回一個正數

const arr = [10, 20, 1, 2]
arr.sort((value1, value2) => {
  if (value1 < value2) {
    return -1
  }
  if (value1 > value2) {
    return 1
  }
  return 0
})
// [1, 2, 10, 20]
console.log(arr)
複製代碼

reverse()

將數組中元素的反轉,並返回該數組。該方法會改變原數組。

const values = [1, 2, 3, 4, 5]
values.reverse()
//[5, 4, 3, 2, 1]
console.log(values)
複製代碼

6、 轉換方法

toLocaleString()

toLocaleString() 返回一個字符串表示數組中的元素。數組中的元素將使用各自的 toLocaleString 方法轉成字符串,這些字符串將使用一個特定語言環境的字符串,並用逗號隔開。

const array1 = [1, 'a', { id: 1 }, new Date()]
// 1,a,[object Object],2020/1/15 上午7:50:38
console.log(array1.toLocaleString())
複製代碼

toString()

返回一個由逗號鏈接起來的字符串。

const array1 = [1, 'abc', { id: 1 }]
// 1,abc,[object Object]
console.log(array1.toString())
複製代碼

join()

將一個數組的全部元素鏈接成一個字符串並返回這個字符串。若是數組只有一個元素,那麼將返回該元素,而不使用分隔符。

Array.join()參數語法:

  1. 第一個參數(可選):指定一個字符串來分隔數組的每一個元素。若是不傳,默認數組元素用逗號(,)分隔。若是是空字符串(""),則全部元素之間都沒有任何字符。
const arr = [1, 2, 3]
// 1,2,3
console.log(arr.join())
// 123
console.log(arr.join(''))
// 1+2+3
console.log(arr.join('+'))
複製代碼

7、 歸併方法(迭代數組的全部項,而後構建一個最終返回的值)

reduce()

reduce()方法從數組的第一項開始,迭代數組的全部元素,構建一個最終返回的值,返回函數累計處理的結果。

Array.reduce()參數語法:

  1. 第一個參數(必填): callback執行數組中每一個值的函數。該函數接收四個參數:
prev cur index array
初始值, 或者上一次調用回調函數返回的值(必填) 當前元素值 (必填) 當前元素的索引值(可選) 數組對象自己(可選)

這個函數返回的任何值都會做爲第一個參數自動傳給下一項。

  1. 第二個參數(可選): initialValue做爲第一次調用callback函數時的第一個參數的值。若是沒有提供初始值,則將使用數組中的第一個元素。在沒有初始值的空數組上調用reduce將報錯。
//Uncaught TypeError: Reduce of empty array with no initial value
 [].reduce(() => {})
複製代碼
const arr = ['L', 'O', 'V', 'E'].reduce((prev, cur) => {
  console.log('prev: ', prev)
  console.log('cur: ', cur)
  return prev + cur
})
// LOVE
console.log(arr)
複製代碼

第一次執行回調函數,prev 是 L,cur 是 O。第二次,prev 是 LO,cur 是 V(數組的第三項)。這個過程會持續到把數組中的每一項都訪問一遍,最後返回結果LOVE。

reduceRight()

reduceRight()reduce()做用相似,使用reduce()仍是reduceRight(),主要取決於要從哪頭開始遍歷數組。除此以外,它們徹底相同。

var values = [1,2,3,4,5]
var sum = values.reduceRight(function(prev, cur, index, array){
  return prev + cur
});
//15
alert(sum)
複製代碼

第一次執行回調函數,prev 是 5,cur 是 4。第二次,prev 是 9(5 加 4 的結果),cur 是 3(數組的第三項)。這個過程會持續到把數組中的每一項都訪問一遍,最後返回結果。

8、demo

實現由短劃線分隔的單詞變成駱駝式的

camelize("background-color") === 'backgroundColor'

function camelize(str) {
  return str
    .split('-') // my-long-word -> ['my', 'long', 'word']
    .map(
      (word, index) => index == 0 ? word : word[0].toUpperCase() + word.slice(1)
    ) // ['my', 'long', 'word'] -> ['my', 'Long', 'Word']
    .join(''); // ['my', 'Long', 'Word'] -> myLongWord
}
複製代碼

數組去重

function unique(arr) {
  let result = [];
  for (let str of arr) {
    if (!result.includes(str)) {
      result.push(str)
    }
  }
  return result
}
複製代碼

在已有的數組上建立一個對象,id做爲鍵,數組的每一項做爲值。

let users = [
  { id: '111', name: "zhangsan", age: 20 },
  { id: '222', name: "lisi", age: 24 },
  { id: '333', name: "wangwu", age: 31 },
]
function groupById(array) {
  return array.reduce((obj, value) => {
    obj[value.id] = value
    return obj
  }, {})
}
/* 
  {
    111: { id: "111", name: "zhangsan", age: 20 },
    222: { id: "222", name: "lisi", age: 24 },
    333: { id: "333", name: "wangwu", age: 31 }
  } 
*/
console.log(groupById(users))
複製代碼

參考連接

JavaScript高級程序設計(第3版)

10 JavaScript array methods you should know

【乾貨】js 數組詳細操做方法及解析合集

數組的擴展

MDN Array www.ecma-international.org/ecma-262/8.…

數組方法

相關文章
相關標籤/搜索