DIV CSS 佈局教程網

JavaScript typeof 運算子:型別判斷的界線
編輯:JavaScript綜合知識     

typeof 是判斷型別最直接的工具,但它有一個讓人印象深刻的特性:幾乎所有物件都只會回報 "object"。理解它的適用範圍,比記住所有回傳值更重要。

基本型別:判斷得很準

var x = 123;
var y = "abc";
var z = true;

typeof x   // "number"
typeof y   // "string"
typeof z   // "boolean"

物件型別:一律是 object

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。

函式:回報 function

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>
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved