2.2 資料型態
可以直接在 console 中來測試觀察。
變數的資料型態
請直接在 console 中,輸入以下各範例來觀察變數的資料型態。
可以用 typeof 來檢測變數的資料類型,包含以下:
字串(String)
用雙引號或單引號括起來的,會被視為字串:
var my_job = "web designer";
typeof my_job; // 回傳 "string"
數值(Number)
數值的部份,例如 1、1.5 等:
var a = 1;
var b = "1";
typeof a; // 回傳 "number"
typeof b; // 回傳 "string"
布靈(Boolean)
true 、 false 就是布靈值:
var c = true;
var d = false;
typeof c; // 回傳 "boolean"
typeof d; // 回傳 "boolean"
物件(Object)
以 左右大括號 括起:
var e = {b: 1};
typeof e; // 回傳 "object"
陣列(Array)
以 左右中括號 括起:
var f = [1, 2]; // 這種較常用
var g = new Array("a", "b", "c"); // 這是另一種寫法
typeof f; // 回傳 "object"
typeof g; // 回傳 "object"
未定義(undefined)
特殊關鍵字:
var h = undefined;
typeof h; // 回傳 "undefined"
空(null)
特殊關鍵字:
var i = null;
typeof i; // 回傳 "object"
函式(function)
var j = function(){
return "a";
};
typeof j; // 回傳 "function"
也可以寫以下這樣,「有名稱的函式」:
function add(){
return "add";
}
typeof add; // 回傳 "function"
總結
以上算起來,利用 typeof 回傳的資料類型,總共六個:
"string"
"number"
"boolean"
"object"
"undefined"
"function"
Last updated