---
# System prepended metadata

title: Typescript 學習筆記2 迴圈控制與條件判斷
tags: [typescript]

---

# Typescript 學習筆記2 迴圈控制與條件判斷

![](https://i.imgur.com/DwTQuYU.png)


## 迴圈

### for loop
就一般的for loop
```typescript=
for(let i:number = 0 ; i < 10 ; i++){
    console.log(i);
}
```
輸出會是
```=
0
1
2
3
4
5
6
7
8
9
```
---
### for...in
簡單來說 i 就會是 index

```typescript=
let a:Array<number> = [1,2,3,4,5,6,7,8,9,10];
for(let i in a){
    console.log(i+" "+a[i])
}
```
輸出會是
```=
0 1
1 2
2 3
3 4
4 5
5 6
6 7
7 8
8 9
9 10
```

- - -
### for...of
很像for...each

```typescript=
let a:Array<number> = [1,2,3,4,5,6,7,8,9,10];

for(let i of a){
    console.log(i)
}

```
輸出會是

```=
1
2
3
4
5
6
7
8
9
10
```
- - -
其他的 while 和 do...while和 Java很像

## 條件控制 ifelse switch
- equal 
    - ``==`` or ``===``
- Not equal
    - ``!=`` or ``!==``
- Not
    - ``!``
- or
    - ``||``
- and
    - ``&&``

另外，`` [1,2] == [1,2] `` 會是 false 喔，如果要比較可以轉成string再比 （踩到的雷）


```typescript=
let a:Array<number> = [1,2,3,4,5,6,7,8,9,10];

let d:[number,string] = [time,a.length.toString()]
console.log(d==[time,a.length.toString()]) // false...... why

switch (d.toString()) {
	case [1,a.length.toString()].toString():
		console.log("n")
		break;
        
	case [3,a.length.toString()].toString():{
		console.log("time++");
		time++;
	}
    
	case [4,a.length.toString()].toString():{
		console.log("hi");
	}

	default:
		console.log("he");
		break;
}

```
比較特別的點是 switch 中可以用
```typescript=
case VALUE:{
    // content here
}
```

這種寫法

###### tags: `typescript`

