Array數組常用方法(含es6)介紹


數組中提供了一系列元素相關的API操作,其中有

三個靜態 api:

  • Array.from()
  • Array.isArray()
  • Array.of()

三十一個原型 api:

  • Array.prototype.concat()
  • Array.prototype.copyWithin()
  • Array.prototype.entries()
  • Array.prototype.every()
  • Array.prototype.fill()
  • Array.prototype.filter()
  • Array.prototype.find()
  • Array.prototype.findIndex()
  • Array.prototype.flat()
  • Array.prototype.flatMap()
  • Array.prototype.forEach()
  • Array.prototype.includes()
  • Array.prototype.indexOf()
  • Array.prototype.join()
  • Array.prototype.keys()
  • Array.prototype.lastIndexOf()
  • Array.prototype.map()
  • Array.prototype.pop()
  • Array.prototype.push()
  • Array.prototype.reduce()
  • Array.prototype.reduceRight()
  • Array.prototype.reverse()
  • Array.prototype.shift()
  • Array.prototype.slice()
  • Array.prototype.some()
  • Array.prototype.sort()

本文整理了自己所用過的數組方法,包括新增的es6語法。

1、Array.from()

將一個類數組或可遍歷對象,轉換成一個新的淺拷貝的數組實例。

let arrayLike = {
    '0': 'a',
    '1': 'b',
    '2': 'c',
    length: 3
}
let arr2 = Array.from(arrayLike)
console.log(arr2) //['a', 'b', 'c']

console.log(Array.from('foo')) // ["f", "o", "o"]

該方法還可以接收第二個參數,作用類似於數組的 map 方法,用來對每個元素進行處理,將處理后的值放入返回的數組。

let arrayLike = {
    '0': 1,
    '1': 2,
    length: 2
}
let newArr = Array.from(arrayLike, item => item * 2)
console.log(newArr) //[2, 4]

2、Array.isArray()

用於檢測是否是一個 Array。

語法:Array.isArray(obj)  參數:obj 需要檢測的值

返回值:如果檢測的值是 Array,則返回 true,否則返回 false

Array.isArray([1, 2, 3]) // true
​
Array.isArray({foo: 123}) // false

3、concat()

合並兩個或多個數組。此方法不會更改原數組,而是返回一個新數組。

const arr1 = ['a', 'b', 'c']
const arr2 = arr1.concat(['d', 'e', 'f'])
​
console.log(arr2) // ["a", "b", "c", "d", "e", "f"]

4、entries()

遍歷數組的鍵和值

const arr = ['a', 'b', 'c'];
const iterator = arr.entries();
for (let e of iterator) {
    console.log(e);   // [0,'a'] [1,'b'] [2,'c']
} 

5、every()

所有的,每一個。檢測數組中的所有元素是否滿足指定條件,如果有一個元素不滿足,則整個表達式返回 false,且剩余的元素不會再進行檢測,要所有的元素都返回了true,結果才是true。every 方法也不會改變原數組。

注意:如果檢測的是一個空數組,在任何情況下返回的都是 false

const arr = [1, 30, 39, 29, 10, 13]
const fn = (currentValue) => currentValue < 40
​
console.log(arr.every(fn)) // true

6、filter()

過濾數組,返回一個滿足條件的新數組。

語法:

arr.filter((item,index,arr) => { // value當前元素,index索引,arr原數組
    // statements
}) 

例:

// 及格的留下來, 沒及格的出門右拐
const students = [
    { name: 'zs', score: 90 },
    { name: 'ls', score: 30 },
    { name: 'ww', score: 10 },
    { name: 'zl', score: 100 },
    { name: 'tq', score: 70 },
    { name: 'wb', score: 60 }
]
​
const result = students.filter(item => {
    return item.score >= 60
})
console.log(result)

7、find()

找到第一個滿足條件的元素。沒有則返回undefined。

const arr = [5, 12, 8, 130, 44]
const found = arr.find(item => item > 10)
​
console.log(found) // 12

8、findIndex()

返回第一個滿足條件的元素的索引。沒找到則返回-1。

const arr = [5, 12, 8, 130, 44]
const isExist = (element) => element > 13
​
console.log(arr.findIndex(isExist)) // 3

9、forEach()

遍歷數組,然后執行一次給定的函數。

注意:forEach() 沒有返回值,本質上等同於 for 循環

const arr = ['毛利蘭', '柯南', '小五郎', '灰原哀']
​
const newArr = []
arr.forEach(item => {
    const temp = <h5>{item}</h5>
    newArr.push(temp)
}) 

10、includes()

判斷數組中是否包含指定的值,如果包含則返回 true,否則返回false。

const pets = ['cat', 'dog', 'bat']
​
console.log(pets.includes('cat')) // true
console.log(pets.includes('at')) // false

11、indexOf()

返回數組中找到的給定元素的第一個索引,如果不存在,則返回-1。

const beasts = ['ant', 'bison', 'camel', 'duck', 'bison']
​
console.log(beasts.indexOf('bison')) // 1
​
// start from index 2
console.log(beasts.indexOf('bison', 2)) // 4
​
console.log(beasts.indexOf('giraffe')) // -1 

12、lastIndexOf()

同indexOf()功能一樣,只不過從數組的后面向前查找,即返回在數組中最后一個的索引。

const animals = ['Dodo', 'Tiger', 'Penguin', 'Dodo']
console.log(animals.lastIndexOf('Dodo')) // 3
​
const arr = [1,2,3,4,5,2]
console.log(arr.lastIndexOf(2))  // 5 

13、join()

將數組中的元素連接成一個字符串並返回。

const elements = ['Fire', 'Air', 'Water']
​
console.log(elements.join()) // "Fire,Air,Water"
console.log(elements.join('-')) // "Fire-Air-Water" 

14、keys()

遍歷數組元素的鍵名。

const arr = ['a', 'b', 'c']
const iterator = arr.keys()
​
for (const key of iterator) {
    console.log(key) // 0, 1, 2
} 

15、values()

遍歷數組元素的鍵值。

const arr = ['a', 'b', 'c']
const iterator = arr.values()
​
for (const value of iterator) {
    console.log(value) // 'a', 'b', 'c'
} 

16、map()

遍歷數組,並返回一個新數組,新數組中包含每次回調函數返回的結果,一比一的得到一個新數組。

語法:

arr.map((value,index,arr) => { //value當前元素,index索引,arr原數組
    // statements
})

例:

const arr = ['毛利蘭', '柯南', '小五郎', '灰原哀']
​
// const newArr = arr.map(item => <h5>{item}</h5>)
const newArr = arr.map(item => {
    return <h5>{item}</h5>
}) 

17、pop()

刪除數組中最后一個元素,並返回該元素的值。此方法會更改原數組。

const plants = ['broccoli', 'cabbage', 'kale', 'tomato']
​
console.log(plants.pop()) // "tomato"
​
console.log(plants) // ["broccoli", "cabbage", "kale"] 

18、push()

在數組的末尾添加一個或多個元素,並返回添加后的數組長度。該方法會改變原數組。

const animals = ['pigs', 'goats', 'sheep']
const count = animals.push('cows')
​
console.log(count) // 4
console.log(animals) // ["pigs", "goats", "sheep", "cows"] 

19、reduce()

方法對數組中的每個元素執行提供的reducer函數,並將其結果計算為一個返回值。更多詳細用法請點這里

const arr = [1, 2, 3, 4]
const reducer = (accumulator, currentValue) => accumulator + currentValue
​
console.log(arr.reduce(reducer)) // 10 = 1 + 2 + 3 + 4
​
console.log(arr.reduce(reducer, 5)) // 15 = 5 + 1 + 2 + 3 + 4

20、reverse()

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

const arr = ['one', 'two', 'three']
const reversed = arr.reverse()
​
console.log(reversed) // ["three", "two", "one"] 

21、shift()

刪除數組中的第一個元素,並返回該元素的值。此方法會改變原數組。

const arr = [1, 2, 3]
const firstElement = arr.shift()
​
console.log(arr) // [2, 3]
console.log(firstElement) // 1  

22、slice()

該方法返回一個新數組,由 begin 和 end 決定的原數組的淺拷貝(包括 begin,不包括end)。不改變原數組。

const animals = ['ant', 'bison', 'camel', 'duck', 'elephant']
​
console.log(animals.slice(2)) // ["camel", "duck", "elephant"]
console.log(animals.slice(2, 4)) // ["camel", "duck"]  

23、some()

檢測數組中滿足指定條件的元素,只要回調函數中有一個或以上返回了 true, 整個結果就是 true。

注意:如果檢測的是一個空數組,在任何情況下返回的都是 true 。

const array = [1, 2, 3, 4, 5]
const even = (element) => element % 2 === 0
​
console.log(array.some(even)) // true  

24、sort()

用原地算法對數組元素進行排序,並返回新數組。默認排列順序是在將元素轉換為字符串,然后比較它們的UTF-16代碼單元值序列時構建的。

const months = ['March', 'Jan', 'Feb', 'Dec']
console.log(months.sort()) // ["Dec", "Feb", "Jan", "March
​
const arr = [1, 30, 4, 21, 100000]
console.log(arr.sort()) // [1, 100000, 21, 30, 4]

25、splice()

刪除指定索引值之后的一個或多個元素或添加新元素。此方法會改變原數組。

// 刪除:第一個參數是從下標為幾的元素開始刪除,第二個參數為刪除幾個元素
var arr = [1, 2, 3, 4, 5]
var res = arr.splice(1, 2) // 從索引為1開始刪除兩個
console.log(arr) // [1,4,5]
console.log(res) // [2,3]
​
​
// 添加:第二個參數設為0,添加第三個參數,表示再插入一個數在指定下標數前面,返回值是空數組
var arr = [1, 2, 3, 4, 5]
var res = arr.splice(2, 0, 6) // 第二個參數為0,在索引為2的前面添加6
console.log(arr) // [1,2,6,3,4,5]
console.log(res) // []
​
​
// 替換:先刪再加,表示替換,返回值是被刪除的元素組成的數組
var arr = [1, 2, 3, 4, 5]
var res = arr.splice(1, 2, 100, 200, 300, 400, 500) // 從索引為1開始刪除兩個,再添加后面的數據
console.log(arr) //[1,100,200,300,400,500,4,5]
console.log(res) //[2,3]  

26、unshift()

在數組的前面添加一個或多個元素,返回值為添加后的新數組長度。該方法會修改原數組。

const arr = [1, 2, 3]
console.log(arr.unshift(4, 5)) // 5
console.log(arr) // [4, 5, 1, 2, 3]  

27、toString()

將數組元素轉換成一個字符串並返回

const array1 = [1, 2, 'a', '1a']
console.log(array1.toString()) // "1,2,a,1a"

 

總結:

會改變原數組的方法:push()、pop()、reverse()、sort()、splice()、shift()、unshift()

 

* forEach():讓每一個元素執行一次函數,沒有返回值,相當於for循環。不會占用全局變量,結合箭頭函數賊舒服

* map():返回一個新數組,長度和原數組一樣。

filter():返回一個新數組,保留那些滿足條件的(即返回值是true的元素)

* some():得到一個布爾值,只要函數中有一個返回true,整體結果就是true

* every():得到一個布爾值,所有的函數都返回true,結果就是true

* includes():返回一個布爾值,如果包含指定值,則返回true

indexOf(),findIndex():得到一個數值,返回找到的第一個元素的索引值,不存在則返回-1

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM