以...為例
let arr = [1,2,3,4] let Arr = [ {id: 0, name: '小明' }, {id: 1, name: '小白' }, {id: 2, name: '小紅' }, {id: 3, name: '小新' } ]
for
for (let i = 0; i < 6; i++) {
}
for in
遍歷數組索引
for (i in arr) { console.log(i); }
// 0、1、2、3
for of
遍歷數組元素值
for (v in arr) { console.log(i); }
// 1、2、3、4
forEach
遍歷數組中的每一項,沒有返回值,對原數組沒有影響
arr.forEach((value,index,arr) => {
}); value 必需,當前元素 index 可選,當前元素的索引值 arr 可選,當前元素所屬的數組對象
indexOf
返回某個指定的值在數組中首次出現的位置
arr.indexOf(value,fromindex)
value 必需,規定需檢索的字符串值。
fromindex 可選的整數參數,規定在字符串中開始檢索的位置
lastIndexOf
返回某個指定的值在數組中最后出現的位置,用法同 indexOf
find
返回一個符合條件的數組第一個元素值
常用語法: arr.find(value,index,arr) => {}) let a = Arr.findIndex(v => v.id === 2) console.log(a); //{ id: 2, name: '小紅', age: 3 }
findIndex
返回一個符合條件的數組第一個元素位置
常用語法: arr.findIndex(value,index,arr) => {})
let a = Arr.findIndex(v => v.id === 2) console.log(a); //2
includes
判斷數組是否包含指定的元素值
arr.includes(value, fromIndex)
value 必須,需要查找的元素值。
fromIndex 可選,從該索引處開始查找
every
檢測數組所有元素是否都符合指定條件,如果數組中檢測到有一個元素不滿足,則整個表達式返回 false
常用語法: arr.every(value,index,arr) => {}) let a = Arr.findIndex(v => v.id > 2) console.log(a); //false
some
檢測數組所有元素是否都符合指定條件,如果有一個元素滿足條件,則表達式返回true
常用語法: arr.some((value,index,arr) => {}) let a = Arr.findIndex(v => v.id > 2) console.log(a); //true
map
返回一個新數組,數組中的元素為原始數組元素調用函數處理后的值,不影響原數組
常用語法: arr.map(value,index,arr) => {}) let a = Arr.map( (v,i) => {
return v.id * i
})
console.log(a); //[ 0, 1, 4, 9 ]
filter
返回一個新的數組,新數組中的元素是通過檢查指定數組中符合條件的所有元素,不影響原數組
常用語法: arr.filter(value,index,arr) => {}) let a = Arr.filter((v,i) => { return v.id > 1 }) console.log(a); //[ { id: 2, name: '小紅', age: 3 } ]
reduce
接收一個函數作為累加器,數組中的每個值(從左到右)開始縮減,最終計算為一個值
常用語法: arr.reduce((total, value, index, arr) => {})
total: 必需,初始值, 或者計算結束后的返回值
let a = arr.reduce((total,v) => {
return total + v
})
console.log(a); //10
reduceRight
和 reduce 功能是一樣的,不同的是 reduceRight() 從數組的末尾向前將數組中的數組項做累加
keys、values、entries
返回一個數組的迭代對象,可以用 for of 進行遍歷
keys遍歷原數組鍵,values遍歷原數組值,entries遍歷原數組鍵值對