> For the complete documentation index, see [llms.txt](https://docs.webmix.cc/javascript-web/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.webmix.cc/javascript-web/2.-ji-ben-guan-nian/2.2-zi-liao-xing-tai.md).

# 2.2 資料型態

可以直接在 console 中來測試觀察。

## 變數的資料型態

請直接在 console 中，輸入以下各範例來觀察變數的資料型態。

可以用 **typeof** 來檢測變數的資料類型，包含以下：

### 字串(String)

用雙引號或單引號括起來的，會被視為字串：

```javascript
var my_job = "web designer";
typeof my_job; // 回傳 "string"
```

### 數值(Number)

數值的部份，例如 1、1.5 等：

```javascript
var a = 1;
var b = "1";
typeof a; // 回傳 "number"
typeof b; // 回傳 "string"
```

### 布靈(Boolean)

true 、 false 就是布靈值：

```javascript
var c = true;
var d = false;
typeof c; // 回傳 "boolean"
typeof d; // 回傳 "boolean"
```

### 物件(Object)

以 **左右大括號** 括起：

```javascript
var e = {b: 1};
typeof e; // 回傳 "object"

delete e.b; // 刪除物件當中的某個屬性
```

### 陣列(Array)

以 **左右中括號** 括起：

```javascript
var f = [1, 2]; // 這種較常用
var g = new Array("a", "b", "c"); // 這是另一種寫法

typeof f; // 回傳 "object"
typeof g; // 回傳 "object"
```

{% hint style="info" %}
JavaScript 總會遇到一些奇怪的行為，像這裡是回傳 "object"，而不是 "array"，也是為人所詬病之處，但這樣的錯誤已經很多年，如果把它修正的話，會造成很多網站會出錯，所以就乾脆不修正。
{% endhint %}

### 未定義(undefined)

特殊關鍵字：

```javascript
var h = undefined;
typeof h; // 回傳 "undefined"
```

### 空(null)

特殊關鍵字：

```javascript
var i = null;
typeof i; // 回傳 "object"
```

{% hint style="info" %}
同陣列，這也是為人所詬病之處。
{% endhint %}

### 函式(function)

```javascript
var j = function(){
  return "a";
};

typeof j; // 回傳 "function"
```

也可以寫以下這樣，「有名稱的函式」：

```javascript
function add(){
  return "add";
}

typeof add; // 回傳 "function"
```

## 總結

以上算起來，利用 **typeof** 回傳的資料類型，總共六個：

* "string"
* "number"
* "boolean"
* "object"
* "undefined"
* "function"
