# 三元運算子/Array Method/迴圈
[TOC]
稅金隨堂練習
let income = 3000000;
let tax;
請依照上表級距,使用if…else...計算出tax是多少
```
let income = 3000000;
let tax;
if(income<=560000){
tax=income*0.05;
}else{
tax=income*0.12;
}
```
* 上述透過三元運算子可以將多行程式碼縮減成一行
### 1. 條件(三元)運算子
(1)格式:條件?值1:值2
(2)當條件符合時,回傳值1,否則回傳值2
(3)隨堂練習改寫
`let tax = income<= 560000?income*0.5:income*0.12;`

多個三元運算子結合
若稅率級距改為下圖

```
let income = 3000000;
let tax = income <= 560000 ? income * 0.5 : ( income < 1260000 ? income * 0.12 : income * 0.2);
console.log(tax);
```

### 2. Array 陣列
(1)可用於存放多筆資料
(2)基本概念:
一個班上有30位學生,該怎麼存全班學生的名字?
```
let student1 = "Jessie";
let student2 = "John";
let student3 = "Jush";
... 不斷創變數?
```
使用 Array 可以同時存放多筆相同類型的資料(元素)
`let students =["Jessie","John","Josh"....];`
Array 的概念如同在大櫃子中加裝門,裡面的櫃子標籤是貼"index(索引)"->流水號數字
我就可以利用標籤,很快的找到我要的東西(像書本前面的索引一樣)

操作方式
#### (1)宣告:let 名稱 = [元素以逗號區隔]
`let students =["Jessie","John","Josh"....];`
#### (2)index(索引):array會自動把裡面的元素從0開始編號,往右+1

#### (3)查看元素:array[索引]
```
let myName = students[0];
```
#### (4)從後方增加元素:array.push(新元素)
students.push("Allen");
會從尾端增加
可增加多個元素array.push(元素1,元素2)
`students.push("Claire","Betty");`
會回傳array的最新長度,可使用變數去接
`let newLength = students.push("Claire","Betty");`
如:原先長度為4,上述程式執行完後,可得newLength=6
#### (5)移除後面的元素:array.pop()
`students.pop();`
會移除最尾端的元素
會回傳被移除的元素
`let out = students.pop();`
如:原先array["Jessie","John","Betty"],上述程式執行完後,可得到out = "Betty",並且array變為["Jessie","John"]
#### (6)從前方增加元素:array.unshift(新元素)
student.unshift("Claire");
可增加多個元素
students.unshift("Dora","Betty");
注意:增加完的過程中,Dora與Betty的順序並不會改變
`let students = ["Dora","Betty","Claire","Jessie","John","Josh","Allen"];`
會回傳array的最新長度,可使用變數去接
#### (7)移除最前面的元素:array.shift()
`student.shift();`
會移除最前端元素
會回傳被移除的元素
`let out = students.shift();`
如:原先array["Jessie","John","Betty"],上述程式執行完後,可以得到out = "Jessie",並且array變為["John","Betty"]
#### (8)移除特定元素:array.splice(開始的索引值,移除的元素數量)
students.splice(2,3) ->從索引值2開始,移除3個元素

會回傳被移除的元素
let out = students.splice(2,3)
如: 原先array["Jessie", "John", "Josh", "Allen", "Claire", "Betty"],上述程式執行完後,可得到out = ["Josh", "Allen", "Claire"],並且array變為["Jessie", "John", "Betty"]
#### (9)取得陣列長度:array.length
let len = students.length;
如: 原先array["Jessie", "John", "Josh", "Allen", "Claire", "Betty"],上述程式執行完後,可得到len = 6
#### (10)反轉陣列:array.reverse()
let.students = ["Amy","Betty","Calvin"];
students.reverse();
上述程式執行完後,可得到students = ["Calvin", "Betty", "Amy"]
#### (11)合併兩個陣列: array.concat(要被合併的陣列)
回傳新的陣列,原本的兩個不受影響

上述程式執行完後,可得到newClass = ["Allen", "Amy", "Anson", "Bella", "Bruce", "Betty“]
### 3.迴圈
情境:該如何印出array裡的所有值?
#### for迴圈
for(expression 1; expression 2; expression 3){// code bliock to be executed}
Expression 1: 在執行迴圈前先執行,通常用來宣告迴圈變數
Expression 2: 執行迴圈的條件 (true才進去迴圈,一旦false就停止)
*** 條件要特別注意! 沒寫好可能會產生無窮迴圈
Expression 3: 每次迴圈執行完後要做的事,通常用來更新迴圈變數
```
for(let i = 0; i < students.length; i++){
console.log(students[i]);
}
```