# 邂逅Javascript

Lesson 2 :  Data Types 資料型態

## 什麼是變數(variable)

box1

box2

box3

box1

box2

box3

Pubgame

3.14159

200

box1

box2

box3

Pubgame

3.14159

200

``````var box1 = "pubgame"; //文字要用雙引號或單引號包住
var box2 = 3.14159;
var box3 = 200;``````

box4

box2

box3

3.14159+200

3.14159

200

``````//有了變數以後，就可以對變數做一些事情
var box2 = 3.14159;
var box3 = 200;

var box4 = box2 + box3;
//box4會等於203.14159``````

## 資料型態：該我登場了

• 字串(String)
• 整數(int)
• 浮點數(float、double)

int是integer的簡稱

float就是浮的意思，中文翻譯是浮點數，但你可以直接看作是小數

double的拗口翻譯是：雙精度浮點數

### 在某些程式語言，變數是需要指定型態的

20

3.14

"hi"

``````int box1 = 20;
float box2 = 3.14;
String box3 = "hi";``````

### 恭喜你，JavaScript沒有這種東西

``````//你只要什麼都用var就好
var box1 = 20;
var box2 = 3.14;
var box3 = "hi";``````

## 但也因為這樣，會有可怕的事情發生...

### 下面這段程式碼，會輸出什麼？

``````var a = "123";
var b = 456;

var c = a+b;
console.log(c);

``````

3. ### 錯誤，不給你執行

``````var number_a = 123;
var string_a = number_a.toString();

var string_b = "456";
var number_b = parseInt(string_b, 10);
``````

## 補充說明

Javascript裡面並沒有分整數或是小數

``````console.log(typeof(123));   //number
console.log(typeof("123")); //string
console.log(typeof(3.14));  //number``````

## 補充說明2

``````var a;
console.log(typeof(a)); //undefined
console.log(typeof(b)); //undefined;``````

## 補充說明3

http://www.ruanyifeng.com/blog/2014/03/undefined-vs-null.html

# 什麼是陣列(Array)?

### 情境：你想要儲存所有員工的名字

``````var people1 = "huli";
var people2 = "tcc";
var people3 = "allen";
....``````

### 陣列：大箱子裡面包很多小箱子

``var peopleList = ["huli", "allen", "tcc" ....];``

huli

allen

tcc

peopleList

### 從陣列裡面拿資料

``````var peopleList = ["huli", "allen", "tcc"];
console.log(peopleList[0]); //huli
console.log(peopleList[1]); //allen
console.log(peopleList.length); //3``````

huli

allen

tcc

peopleList

0

1

2

index

## HW #1

1.讓使用者輸入兩個數字，輸出相加後的結果

Hint: var a = prompt("請輸入數字");

可跳出視窗讓使用者輸入數字

2. 構造出一個有7個元素的陣列，內容是星期一到星期日

並且印出陣列的長度

Hint: var weekday = [ ... ];

By huli

• 559