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