## 數組 - 常用方法
- indexOf():查詢元素在數組中首次出現的位置,沒有則返回 -1
```
const arr = [1, 2, 3]
const i = arr.indexOf(2) // i = 1
const j = arr.indexOf(4) // j = -1
const k = arr.indexOf(2, 2) // k = -1 (從下標為 2 的位置開始找,所以找不到)
```
- concat():合并兩個或多個數組
```
const arr = [1, 2, 3], arr2 = [4, 5], arr3 = [6, 7]
arr.concat(arr2) // [1, 2, 3, 4, 5]
arr.concat(arr2, arr3) // [1, 2, 3, 4, 5, 6, 7]
```
- join():將數組元素轉換成字符串(默認以逗號分隔)
```
const arr = [1, 2, 3]
arr.join() // "1,2,3"
arr.join(' ') // "1 2 3"
```
- forEach():遍歷數組
```
const arr = [1, 2, 3]
arr.forEach((item, index, arr)=>{// index 和 arr 都是可選項
console.log(item, index, arr) // 1, 0, [1,2,3] ...
})
```
- map():遍歷數組,返回處理后的新數組
```
const arr = [1, 2, 3]
arr.map((item, index, arr)=>{// index 和 arr 都是可選項
return item+1
})
console.log(arr) // [2,3,4]
```
- some():遍歷數組,判斷數組某項是否滿足條件(條件滿足后不再遍歷下去),返回 true / false
```
const arr = [1, 2, 3]
const bol = arr.some((item, index, arr)=>{// index 和 arr 都是可選項
return item>=2
})
console.log(bol) // true
```
- every():遍歷數組,判斷數組全部元素是否滿足條件,返回 true / false
```
const arr = [1, 2, 3]
const bol = arr.every((item, index, arr)=>{// index 和 arr 都是可選項
return item>2
})
console.log(bol) // false
```
- filter():遍歷數組,返回滿足條件后的新數組
```
const arr = [1, 2, 3]
arr.filter((item, index, arr)=>{// index 和 arr 都是可選項
return item>1
})
console.log(arr) // [2,3]
```
- sort():對數組進行排序
- reverse():反轉數組
- push():向數組末尾添加一個或多個元素
- pop():刪除數組最后一個元素并返回刪除元素
- shift():刪除數組第一個元素并返回刪除元素