一、改變原數組
- push:向數組尾部添加元素,返回添加後數組的長度。
- pop:去除數組最後一個元素,返回被去除的元素。
- shift: 去除數組第一個元素,返回被去除的元素。
- unshift:向數組頭部添加元素,返回添加後數組的長度。
- reverse:數組倒序,返回順序完全相反的數組。
- sort:數組排序(默認是從小到大),返回排序後的數組。
- splice:方法向/從數組中添加/刪除項目,返回被刪除的項目。
方法大家都知道,但是返回可能就容易被人忽略。
代碼:
var arr = [2,4,5,6]
// push
// console.log(arr.push(1)) 5
// pop
// console.log(arr.pop()) 6
// shift
// console.log(arr.shift()) 2
// unshift
// console.log(arr.pop('1')) 5
// reverse
// console.log(arr.reverse()) [6, 5, 4, 2]
// sort
// sort默認情況下是返回從小到大,如果你想返回從大到小。可以向下面這樣寫
// console.log(arr.sort()) [2,4,5,6]
// console.log(arr.sort((a,b)=> b-a)) [6, 5, 4, 2]
// splice
// console.log(arr.splice(2,1,3)) 返回[5],原數組變爲 [2, 4, 3, 6]
二、數組遍歷方法
先假設一組數據:
var potatos = [
{ id: '1001', weight: 50 },
{ id: '1002', weight: 80 },
{ id: '1003', weight: 120 },
{ id: '1004', weight: 40 },
{ id: '1005', weight: 110 },
{ id: '1006', weight: 60 }
]
1、forEach()方法和map()方法—遍歷
兩種方法都是對數組的遍歷,但是不同的是map方法有返回值。如果不需要返回的話,語義上使用forEach方法更合適。
// forEach: 對數組每一個項進行操作,返回undefined
potatos.forEach(potato => potato.weight += 20 )
// map: 對數組每一個項進行操作,並返回操作後的結果
w = potatos.map(potato => { return potato.weight += 20 })
//[ 70, 100, 140, 60, 130, 80 ]
注意:forEach不能break也不能return!
2、filter()方法—遍歷篩選
filter方法主要做的就是篩選過濾的事,看單詞就能知道他的作用。
var bigOnes = potatos.filter(potato => { return potato.weight > 100 })
// [ { id: '1003', weight: 120 }, { id: '1005', weight: 110 } ]
// 返回滿足條件的數組,並不改變原數組
3、some()方法—某一個符合
當只需要判斷數組中有沒有符合條件的時候(一個就行) 就需要我們的some方法登場了。返回的是true或false,相當於有或者無。
var hasbig = potatos.some(potato => { return potato.weight > 100 })
//true
只要找到一個符合條件的,就會返回true 。所以並不會全部遍歷。
4、every()方法—全符合
判斷數組中的項,是否全部符合某種條件。當有某一個不符合時,直接返回false。
var allbig = potatos.every(potato => { return potato.weight > 100 })
//false
5、find()方法—返回第一個符合的項
find和some很類似,都是尋找符合條件的,有一個就可以 不過some進去搜羅了一圈回來報了個“有”(true),而find則把那個抱出來(返回第一個符合條件的對象)
var big = potatos.find(potato => { return potato.weight > 100 })
//{ id: '1003', weight: 120 }
6、findIndex()方法—返回第一個符合的項的index值
findIndex方法的原理和find的一樣只是返回的東西不一樣,findIndex返回的是index
var i = potatos.findIndex(potato=>{ return potato.weight > 100 })
//2
findIndex返回第一個符合條件的索引號
7、reduce()—遞歸累加
var sum = potatos.reduce((sum, p) =>
{ return p.weight + sum },0)
//460
//並不會改變原數組
reduce()方法接收一個回調函數作爲第一個參數,回調函數又接受四個參數,分別是;
- previousValue =>初始值或上一次回調函數疊加的值;
- currentValue => 本次回調(循環)將要執行的值;
- index=>“currentValue”的索引值;
- arr => 數組本身;
reduce()方法返回的是最後一次調用回調函數的返回值;
reduce()還有一些很棒的高階應用,具體大家可以去查閱相關資料看看。