typeof 是判斷型別最直接的工具,但它有一個讓人印象深刻的特性:幾乎所有物件都只會回報 "object"。理解它的適用範圍,比記住所有回傳值更重要。
var x = 123;
var y = "abc";
var z = true;
typeof x // "number"
typeof y // "string"
typeof z // "boolean"
var arr = new Array();
var date = new Date();
var str = new String("abc");
typeof arr // "object"
typeof date // "object"
typeof str // "object"
陣列、日期、包裝物件全都只回 "object"。想分辨陣列該用 Array.isArray(),判斷日期則看 instanceof Date。
JavaScript 裡用 function 來模擬「類」的概念,而函式本身也是一種可被 typeof 正確辨識的型別:
typeof Array // "function"
typeof Date // "function"
typeof String // "function"
這裡容易誤解:Array、Date、String 是建構函式,所以 typeof 得到 "function";而 new Array() 產生的實例才是 "object"。
<html>
<head>
<title>javascript 中 typeof 的使用</title>
<script>
// 1、基本型別
var x = 123;
var y = "abc";
var z = true;
// alert(typeof x); // number
// alert(typeof y); // string
// alert(typeof z); // boolean
// 2、引用型別,型別都是 object
var arr = new Array();
var date = new Date();
var str = new String("abc");
// alert(typeof arr); // object
// alert(typeof date); // object
// alert(typeof str); // object
// 3、建構函式本身,型別是 function
alert(typeof Array); // function
alert(typeof Date); // function
alert(typeof String); // function
</script>
</head>
<body>
</body>
</html>