數組的方法及使用方法(包含ES5,ES6)


1、concat

concat() 方法用於連接兩個或多個數組。

該方法不會改變現有的數組,而僅僅會返回被連接數組的一個副本。

語法:arrayObject.concat(array,......,array)

參數 描述
arrayX 必需。該參數可以是具體的值,也可以是數組對象。可以是任意多個。
const arr = [1,2,3] const brr = [4,5] const crr = [6,7] const drr = arr.concat(brr) const err = arr.concat(brr,crr) console.log(drr) //[1,2,3,4,5]
console.log(err)  //[1,2,3,4,5,6,7]

2、join

join() 方法用於把數組中的所有元素放入一個字符串。

元素是通過指定的分隔符進行分隔的。

語法:arrayObject.join(separator)  

 

參數 描述
separator 可選。指定要使用的分隔符。如果省略該參數,則使用逗號作為分隔符。

const arr = [1,2,3] console.log(arr.join(',')) // 1,2,3

3、pop

pop() 方法用於刪除並返回數組的最后一個元素,會改變原數組。

語法:arrayObject.pop()

const arr = [1,2,3] const brr =arr.pop() //3
console.log(arr) //[1,2]

4、push

push() 方法可向數組的末尾添加一個或多個元素,並返回新的長度。

語法:arrayObject.push(newelement1,newelement2,....,newelementX)

參數 描述
newelement1 必需。要添加到數組的第一個元素。
newelement2 可選。要添加到數組的第二個元素。
newelementX 可選。可添加多個元素。
const arr = [1, 2, 3] const brr = [4, 5] const obj = {         name: 'shy',         age: '22'     } const a = arr.push(brr) const b = arr.push(obj) console.log(arr) //[1, 2, 3, [4,5]]
console.log(arr) //[1, 2, 3, { name:'shy',age:'22'}]
console.log(arr) //[1, 2, 3, [4,5],{ name:'shy',age:'22'}]

5、reverse

reverse() 方法用於顛倒數組中元素的順序。

語法:arrayObject.reverse()

const arr = [1,2,'a'] const brr = arr.reverse() console.log(brr) //['a',2,1]

6、shift

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

語法:arrayObject.shift()

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

7、slice

slice() 方法可從已有的數組中返回選定的元素

語法:arrayObject.slice(start,end)

 

參數 描述
start 必需。規定從何處開始選取。如果是負數,那么它規定從數組尾部開始算起的位置。也就是說,-1 指最后一個元素,-2 指倒數第二個元素,以此類推。
end 可選。規定從何處結束選取。該參數是數組片斷結束處的數組下標。如果沒有指定該參數,那么切分的數組包含從 start 到數組結束的所有元素。如果這個參數是負數,那么它規定的是從數組尾部開始算起的元素。

可使用負值從數組的尾部選取元素如果 end 未被規定,那么 slice() 方法會選取從 start 到數組結尾的所有元素

const arr = [1,2,3] const brr = arr.slice(0,1) const crr = arr.slice(0) const drr = arr.slice(0,-1) console.log(brr)//[1]
console.log(crr) //[1,2,3]
console.log(drr) //[1,2]

8、sort

sort() 方法用於對數組的元素進行排序。

語法:arrayObject.sort(sortby)

參數 描述
sortby 可選。規定排序順序。必須是函數。
  function sortNumber(a, b) {         return a - b     }     const arr = [6, 1564, 15, 234, 4, 345, 1, 5, 35, 48]     const brr = ['Aads', 'Bd', 'AD', 'JF', 'XFG']     console.log(brr.sort()) //["AD", "Aads", "Bd", "JF", "XFG"]
    console.log(arr.sort())  //[1, 15, 1564, 234, 345, 35, 4, 48, 5, 6]
    console.log(arr.sort(sortNumber))//[1, 4, 5, 6, 15, 35, 48, 234, 345, 1564]

9、splice

splice() 方法向/從數組中添加/刪除項目,然后返回被刪除的項目

語法:arrayObject.splice(index,howmany,item1,.....,itemX)

 

參數 描述
index 必需。整數,規定添加/刪除項目的位置,使用負數可從數組結尾處規定位置。
howmany 必需。要刪除的項目數量。如果設置為 0,則不會刪除項目。
item1, ..., itemX 可選。向數組添加的新項目。
const arr = [1, 2, 3] const btt = arr.splice(0,1) //刪除第一項
const crr = arr.splice(0,1,"a") //替換
const drr = arr.splice(2, 0, [4, 5])//增加
console.log(arr) //[2, 3]
console.log(arr)  //["a", 2, 3]
console.log(arr)  //[1, 2,[4,5], 3]

10、toString

toString() 方法可把數組轉換為字符串,並返回結果。

語法:arrayObject.toString()

const arr = [1, 'a', 'SAD'] console.log(arr.toString()) //1,a,SAD

11、unshift

unshift() 方法可向數組的開頭添加一個或更多元素,並返回新的長度。

語法:arrayObject.unshift(newelement1,newelement2,......,newelementX)

 

參數 描述
newelement1 必需。向數組添加的第一個元素。
newelement2 可選。向數組添加的第二個元素。
newelementX 可選。可添加若干個元素。
const arr = [1, 2, 3] const brr = [4, 5] const obj = {        name: 'shy',        age: '22'    } const a = arr.unshift(brr) const b = arr.unshift(obj) console.log(arr) //[[4,5],1, 2, 3]
console.log(arr) //[{ name:'shy',age:'22'},1, 2, 3 ]
console.log(arr) //[ { name:'shy',age:'22'},[4,5],1, 2, 3]

ES5部分

12、Array.isArray()//判斷是不是一個數組

 

語法:Array.isArray(arrayObject)

const arr = [1,'a',{name:'shy'}] console.log(Array.isArray(arr)) //true

13、Array.forEach() //遍歷數組

語法:array1.forEach(callbackfn[, thisArg])

 

參數 描述
array1 必選。一個數組對象。
callbackfn 必選。最多可以接受三個參數的函數。對於數組中的每個元素,forEach 都會調用 callbackfn 函數一次。
thisArg 可選。 callbackfn 函數中的 this 關鍵字可引用的對象。如果省略 thisArg,則 undefined 將用作 this 值。

 

回調函數的形參,依次為,value:遍歷的數組內容;index:對應的數組索引,array:數組本身。

    const arr = [1, 'a', { name: 'shy' }] function myFunction(value, index, array) { //console.log(value) //1 a  {name: "shy"}
        //console.log(index) // 0 1 2
        console.log(array)  // [1, 'a', { name: 'shy' }] [1, 'a', { name: 'shy' }] [1, 'a', { name: 'shy' }]
 } arr.forEach(myFunction)

14、Array.map() //遍歷數組

語法:array1.map(callbackfn[, thisArg])

 

參數 描述
array1 必選。一個數組對象。
callbackfn 必選。最多可以接受三個參數的函數。對於數組中的每個元素,forEach 都會調用 callbackfn 函數一次。
thisArg 可選。 callbackfn 函數中的 this 關鍵字可引用的對象。如果省略 thisArg,則 undefined 將用作 this 值。

 

回調函數的形參,依次為,value:遍歷的數組內容;index:對應的數組索引,array:數組本身。

    const arr = [1, 'a', { name: 'shy' }] function myFunction(value, index, array) { //console.log(value) //1 a  {name: "shy"}
        //console.log(index) // 0 1 2
        //console.log(array) // [1, 'a', { name: 'shy' }] [1, 'a', { name: 'shy' }] [1, 'a', { name: 'shy' }]
 } arr.map(myFunction)

map與forEach的異同

相同點

  • 都是循環遍歷數組中的每一項
  • forEach和map方法里每次執行匿名函數都支持3個參數,參數分別是item(當前每一項),index(索引值),arr(原數組)
  • 匿名函數中的this都是指向window
  • 只能遍歷數組
  • 都不會改變原數組

區別

map方法

1.map方法返回一個新的數組,數組中的元素為原始數組調用函數處理后的值。

2.map方法不會對空數組進行檢測側,map方法不會改變原數組。

3.map支持return返回值,也不影響原數組,但是會返回一個新的數組。

4.若arr為空數組,則map方法返回的也是一個空數組。

forEach方法

1.forEach方法用來調用數組的每個元素,將元素傳給回調函數。

2.forEach對於空數組是不會調用回調函數的,無論arr是不是空數組,forEach返回的都是undefined。這個方法只是將數組中的每一項作為callback的參數執行一次。

3.forEach不支持return,對原來的數組也沒有影響。但是我們可以自己通過數組的索引來修改原來的數組。

 

15、Array.filter() //過濾

語法:arr.filter(callback(element[, index[, array]])[, thisArg])

參數

描述

callback

必選。用來測試數組的每個元素的函數。返回 true 表示該元素通過測試,保留該元素,false 則不保留。它接受以下三個參數:

element

數組中當前正在處理的元素。

index

可選。正在處理的元素在數組中的索引。

array

調用了 filter 的數組本身。

thisArg

執行 callback 時,用於 this 的值

    const arr = [45, 4, 9, 16, 25];     function myFunction(value) {         return value > 18;     }    console.log(arr.filter(myFunction)) //[45, 25]

16、Array.reduce() 

方法對累加器和數組中的每個元素 (從左到右)應用一個函數,將其減少為單個值。

語法:array.reduce(callbackfn,[initialValue])

reduce()方法接收callbackfn函數,而這個函數包含四個參數:

function callbackfn(preValue,curValue,index,array){}

參數

描述

callback

必選。回調函數

preValue

上一次調用回調返回的值,或者是提供的初始值(initialValue)

curValue

數組中當前被處理的數組項

index

當前數組項在數組中的索引值

array

調用 reduce()方法的數組

initialValue

可選項,其值用於第一次調用 callback 的第一個參數。如果沒有設置初始值,則將數組中的第一個元素作為初始值

空數組調用reduce時沒有設置初始值將會報錯

//1.數組元素求和
const arr = [1, 2, 3, 4, 5] const brr = arr.reduce((a, b) => a+b) console.log(brr) //15 //2.二維數組轉化為一維數組
const arr = [[1, 2], [3, 4], [5, 6]] const brr = arr.reduce((a, b) => a.concat(b),[]) console.log(brr) //[1, 2, 3, 4, 5, 6] //3.計算數組中元素出現的次數
const arr = [1, 2, 3, 1, 2, 3, 4] const brr = arr.reduce((items, item) => {    if(item in items){         items[item]++;     }else{         items[item] = 1;     }     return items; },{})  console.log(brr)//{1: 2, 2: 2, 3: 2, 4: 1} //4.數組去重
const arr = [1, 2, 3, 1, 2, 3, 4, 4, 5] const brr = arr.reduce((init, current) => {     if(init.length === 0 || init.indexOf(current) === -1){         init.push(current);     }     return init; },[])  console.log(brr)//[1, 2, 3, 4, 5] //5.數組去重
const arr = [1, 2, 3, 1, 2, 3, 4, 4, 5] const brr = arr.sort().reduce((init, current) => {     if(init.length === 0 || init[init.length-1] !== current){         init.push(current);     }     return init; },[]) //[1, 2, 3, 4, 5]console.log(brr)//6.求最大\小值 
const arr = [1,2,3,4,5] const brr = arr.reduce((a, b) =>Math.max(a,b)) const crr = arr.reduce((a, b) =>Math.min(a,b)) console.log(brr)//5
console.log(crr)//1

17、Array.reduceRight()

方法對累加器和數組中的每個元素 (從右到左)應用一個函數,將其減少為單個值。

語法:array.reduceRight(callbackfn,[initialValue])

reduce()方法接收callbackfn函數,而這個函數包含四個參數:

function callbackfn(preValue,curValue,index,array){}

參數

描述

callback

必選。回調函數

preValue

上一次調用回調返回的值,或者是提供的初始值(initialValue)

curValue

數組中當前被處理的數組項

index

當前數組項在數組中的索引值

array

調用 reduce()方法的數組

initialValue

可選項,其值用於第一次調用 callback 的第一個參數。如果沒有設置初始值,則將數組中的第一個元素作為初始值

空數組調用reduceRight時沒有設置初始值將會報錯

//1.數組元素求和
const arr = [1, 2, 3, 4, 5] const brr = arr.reduceRight((a, b) => a+b) console.log(brr) //15 //2.二維數組轉化為一維數組
const arr = [[1, 2], [3, 4], [5, 6]] const brr = arr.reduceRight((a, b) => a.concat(b),[]) console.log(brr) // [5, 6, 3, 4, 1, 2] //3.計算數組中元素出現的次數
const arr = [1, 2, 3, 1, 2, 3, 4] const brr = arr.reduceRight((items, item) => {    if(item in items){         items[item]++;     }else{         items[item] = 1;     }     return items; },{})  console.log(brr)//{1: 2, 2: 2, 3: 2, 4: 1} //4.數組去重
const arr = [1, 2, 3, 1, 2, 3, 4, 4, 5] const brr = arr.reduceRight((init, current) => {     if(init.length === 0 || init.indexOf(current) === -1){         init.push(current);     }     return init; },[])  console.log(brr)//[1, 2, 3, 4, 5] //5.數組去重
const arr = [1, 2, 3, 1, 2, 3, 4, 4, 5] const brr = arr.sort().reduceRight((init, current) => {     if(init.length === 0 || init[init.length-1] !== current){         init.push(current);     }     return init; },[]) //[1, 2, 3, 4, 5]console.log(brr)//6.求最大\小值 
const arr = [1,2,3,4,5] const brr = arr.reduceRight((a, b) =>Math.max(a,b)) const crr = arr.reduceRight((a, b) =>Math.min(a,b)) console.log(brr)//5
console.log(crr)//1

18、Array.every()

方法用於檢測數組中所有元素是否都符合指定條件,若符合返回true,否則返回false

語法:array.every(function(item,index,array){

                 //item:當前元素的值;

                    //index:當前元素的索引;

                    // array:當前元素的數組對象;

                })

every()方法使用指定函數檢測數組中的所有元素;

如果數組中檢測到有一個元素不滿足,則整個表達式返回false,且剩余的元素不會再進行檢測。如果所有元素都滿足條件,則返回true;

注意every()不會對空數組進行檢測;

           every()不會改變原來的數組

    const arr = [1, 2, 3, 4, 5, 15, 456, 489, 1234]     function checkArr(arr) {         //   return arr>= 18;//false
        return arr>= 1; //true    }
    const brr = arr.every(checkArr)     console.log(brr)

19、Array.some()

方法用於檢測數組中的元素是否有滿足指定條件的,若滿足返回true,否則返回false;

語法:array.some(function(item,index,array){

//item:當前元素的值;

                    //index:當前元素的索引;

                    // array:當前元素的數組對象;

                })

some()方法會依次執行數組的每個元素;

如果有一個元素滿足條件,則表達式返回true,剩余的元素不會再執行檢測。如果沒有滿足條件的元素,則返回false

注意:some()不會對空數組進行檢測;

           some()不會改變原始數組;

  const arr = [1, 2, 3, 4, 5, 15, 456, 489, 1234]     function checkArr(arr) {         //   return arr >= 46889;//false
        return arr >= 18; //true    }
    const brr = arr.some(checkArr)     console.log(brr)

20、Array.indexOf()

該方法返回某個元素在數組中的位置。

語法:array.indexOf(item,start)

參數:item:必需。規定需檢索的字符串值。

 Start:可選的整數參數。規定在數組中開始檢索的位置。它的合法取值是 0 到 stringObject.length - 1。如省略該參數,則將從字符串的首字符開始檢索。

  const arr = [1,2,3,5,4,3,6,4];    //索引值: 0 1 2 3 4 5 6 7 
     console.log(arr.indexOf(3)); //2
     console.log(arr.indexOf(3,2)); //2
     console.log(arr.indexOf("4")); //-1
     console.log(arr.indexOf(4,3)); //4

1.只有一個參數時,IndexOf從前往后找第一個item,找到就返回索引值。例如:arr.IndexOf(3)-----從z左到右找第一個3,索引值為2,所以結果就是2。

2.兩個參數時,arr.IndexOf(3,2)------ 在索引 0---2之后找第一個3,其索引值為2,所以結果就是2。 arr.IndexOf(4,3)------在索引 0---3之后找第一個4,其索引值為4,所以結果就是4。

3.arr.IndexOf("4")------ 因為查找的是字符串"5",所以找不到返回 -1

 

21、Array.lastIndexOf()

該方法返回某個元素在數組中的位置。

語法:array.lastIndexOf(item,start)用法與Array.indexOf()類似

     const arr = [1,2,3,5,4,3,6,4];         //索引值: 0 1 2 3 4 5 6 7 
     console.log(arr.lastIndexOf(3)); //5
     console.log(arr.lastIndexOf(3,2)); //2
     console.log(arr.lastIndexOf("4")); //-1
     console.log(arr.lastIndexOf(4,6)); //4

1.只有一個參數時,lastIndexOf從右向左找第一個item,找到就返回索引值。例如:arr.lastIndexOf(3)-----從右向左找第一個3,索引值為5,所以結果就是5。

2.兩個參數時,arr.lastIndexOf(3,2)------在索引0---2之間找3,其索引值為2,所以結果就是2。 arr.lastIndexOf(4,6)------在索引0---6之間找4,其索引值為4,所以結果就是4

 

ES6

22、Array.find()

查找數組內元素,找到第一個符合條件的數組成員,返回該成員的值,如果沒有找到,返回undefined

語法:arr.find(function(item,index,array){

              //item:當前元素的值;

                                  //index:當前元素的索引;

                                 // array:當前元素的數組對象;

                            })

const arr = [1, 2, 3, 4, 5, 6] const brr = arr.find((value, index, arr) => {        return value > 3 //4
       return value <-2 //undefined    })
console.log(brr) // 4

23、Array.findIndex()

Array.findIndex():找到滿足條件的第一個元素,返回其位置,如果未找到,則返回-1。

語法:arr.findIndex(function(item,index,array){

              //item:當前元素的值;

                                    //index:當前元素的索引;

                                   // array:當前元素的數組對象;

                })

    const arr = [1, 2, 3, 4, 5, 6]     const brr = arr.findIndex((value, index, arr) => {         return value > 3 //3
        return value <-2 //-1    })
    console.log(brr) // 3

24、Array.from()

 Array.from()方法就是將一個類數組對象或者可遍歷對象轉換成一個真正的數組。

  那么什么是類數組對象呢?所謂類數組對象,最基本的要求就是具有length屬性的對象。

  1、將類數組對象轉換為真正數組:

    const arr = { 0: 'shy', 1: '22', 2: [1, 2, 'a'], 'length': 3 } const brr = Array.from(arr) console.log(brr) //["shy", "22", [1,2,'a']]

 

 那么,如果將上面代碼中length屬性去掉呢?實踐證明,答案會是一個長度為0的空數組。

  這里將代碼再改一下,就是具有length屬性,但是對象的屬性名不再是數字類型的,而是其他字符串型的,代碼如下:

    const arr = { 'name': 'shy', 'age': '22', 'array': [1, 2, 'a'], length: 3 } const brr = Array.from(arr) console.log(brr) // [ undefined, undefined, undefined ]

 

 會發現結果是長度為3,元素均為undefined的數組

  由此可見,要將一個類數組對象轉換為一個真正的數組,必須具備以下條件:

  1、該類數組對象必須具有length屬性,用於指定數組的長度。如果沒有length屬性,那么轉換后的數組是一個空數組。

  2、該類數組對象的屬性名必須為數值型或字符串型的數字

  ps: 該類數組對象的屬性名可以加引號,也可以不加引號

 

  2、將Set結構的數據轉換為真正的數組: 

const arr = [1, 2, 3, 4, 5, 6] const set = new Set(arr) const brr = Array.from(set) console.log(brr) // [1, 2, 3, 4, 5, 6]

 

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

 const arr = [1, 2, 3, 4, 5, 6] const set = new Set(arr) const brr = Array.from(set, item => item + 1) console.log(brr) // [2, 3, 4, 5, 6, 7]

 

3、將字符串轉換為數組:

    const str = 'hello world!' const arr = Array.from(str) console.log(arr) //["h", "e", "l", "l", "o", " ", "w", "o", "r", "l", "d", "!"]

 

4、Array.from參數是一個真正的數組:

    const arr = Array.from([1, 2, 3, 4, 5, 6, 'a']) console.log(arr) // [1, 2, 3, 4, 5, 6, "a"]

 

像這種情況,Array.from會返回一個一模一樣的新數組

25、Array.of(): 把一組值,轉成數組

    console.log(Array.of(1, 2, 'a')) //[1, 2, "a"]
 console.log(Array.of('a')) // ["a"]
 console.log(Array.of('a').length) // 1

這個方法的主要目的,是彌補數組構造函數Array()的不足。因為參數個數的不同,會導致Array()的行為有差異。

    console.log(Array()) // []
 console.log(Array(3)) // [,,,]
 console.log(Array('a')) //["a"]
 console.log(Array(1, 2, 3)) // [1, 2, 3]

上面代碼中,Array方法沒有參數、一個參數、三個參數時,返回結果都不一樣。只有當參數個數不少於 2 個時,Array()才會返回由參數組成的新數組。參數個數只有一個時,實際上是指定數組的長度。

Array.of基本上可以用來替代Array()new Array(),並且不存在由於參數不同而導致的重載。它的行為非常統一。

console.log(Array.of()) // []
 console.log(Array.of(undefined)) // [undefined]
 console.log(Array.of('a')) // ['a']
 console.log(Array.of(1, 2)) // [1, 2]

Array.of()總是返回參數值組成的數組。如果沒有參數,就返回一個空數組。

 

26、arr.fill() 填充

使用制定的元素填充數組,其實就是用默認內容初始化數組。

語法:arr.fill(value, start, end)

value:填充值。

start:填充起始位置,可以省略。

end:填充結束位置,可以省略,實際結束位置是end-1

無起止位置

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

有開始位置

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

有起止位置

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

 

 

27、arr.includes() // 查找指定元素是否存在,如果存在,返回true,如果不存在返回false

語法:arr.includes(searchElement, fromIndex)

searchElement:必須。需要查找的元素值。

fromIndex:可選。表示判斷的起始位置。從該索引處開始查找 searchElement。

如果為負值,則按升序從 array.length + fromIndex 的索引開始搜索。默認為 0。

    const arr = [1, 'a', 'cj', NaN]; console.log(arr.includes("a"));//true
 console.log(arr.includes(NaN));//true
 console.log(arr.includes("a", 0));//true
 console.log(arr.includes("a", 2));//false 

1.只有一個參數時,IndexOf從前往后找第一個item,找到就返回索引值。例如:arr.IndexOf(3)   -----   從z左到右找第一個3,索引值為2,所以結果就是2。

2.兩個參數時,arr.IndexOf(32)  ------  在索引 0---2之后找第一個3,其索引值為2,所以結果就是2。 arr.IndexOf(43)  ------  在索引 0---3之后找第一個4,其索引值為4,所以結果就是4

3.arr.IndexOf("4")  ------  因為查找的是字符串"5",所以找不到返回 -1


免責聲明!

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



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