---
# System prepended metadata

title: 陣列操作
tags: [ALPHACampWeek1]

---

###### tags: `ALPHACampWeek1`

陣列操作
===

頭尾陣列操作
---
const nums = [0, 1, 2, 3, 4]

nums.pop()
console.log(nums) // [0, 1, 2, 3]

nums.push(5)
console.log(nums) // [0, 1, 2, 3, 5]

nums.shift()
console.log(nums) // [1, 2, 3, 5]

nums.unshift(0.5)
console.log(nums) // [0.5, 1, 2, 3, 5]

從中間修改陣列操作
---
const nums = [0, 1, 2, 3, 4]
nums.splice(2, 0, 99)
console.log(nums) // [0, 1, 99, 2, 3, 4]

連結多個陣列操作 concat
---
let daysOfWeek = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
daysOfWeek.concat(['Saturday', 'Sunday'])

splice v.s. slice
---
splice(起始值,刪除幾個,新增的數字)=>會回傳陣列

- splice片段可以賦值
const drawWinner = players.splice(index, 1)

slice(起始值,結束值)

查看陣列是否包含某個值 includes
---
Input : [1, 2, 3, 4, 5].includes(2);
Output: true

Input : [1, 2, 3, 4, 5].includes(9);
Output: false

陣列迭代(他宣告了一個匿名function)
---
- Array.forEach()
var numbers = [45, 4, 9, 16, 25];
numbers.forEach(function(value, index){ // 參數若沒有用到，可以省略不寫
  console.log(value);
});

- Array.map()
var numbers = [45, 4, 9, 16, 25];
var numbers2 = numbers.map(function(value, index){
  return value * 2;
});
console.log(numbers); // [45, 4, 9, 16, 25]
console.log(numbers2); // [90, 8, 18, 32, 50]