DIV CSS 佈局教程網

JavaScript 中的型別判斷方法
編輯:JavaScript基礎知識     

在 JavaScript 裡,typeof 是最直覺的型別判斷方式,但它只能區分基本型別,也就是 "number"、"string"、"undefined"、"boolean"、"object" 這五種。

問題在於,對於陣列、函數、物件,typeof 一律會回傳 "object",無法細分。若要判斷複合資料型別,可以借助 instanceof:

var a = {};            // 物件
var b = [];            // 陣列
var c = function () {}; // 函數

// 物件
(a instanceof Object) && !(a instanceof Function)
// 陣列
(a instanceof Object) && (a instanceof Array)
// 函數
(a instanceof Object) && (a instanceof Function)

更簡便的方式

其實最通用、最可靠的判斷方式,是使用 Object.prototype.toString.call():

console.log(Object.prototype.toString.call(123));        // [object Number]
console.log(Object.prototype.toString.call('123'));       // [object String]
console.log(Object.prototype.toString.call(undefined));   // [object Undefined]
console.log(Object.prototype.toString.call(true));        // [object Boolean]
console.log(Object.prototype.toString.call({}));          // [object Object]
console.log(Object.prototype.toString.call([]));          // [object Array]
console.log(Object.prototype.toString.call(function () {})); // [object Function]

這個方法幾乎能準確判斷所有型別,是型別檢測中值得推薦的做法。

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