DIV CSS 佈局教程網

六個小函式搞定 JavaScript 型別判斷
編輯:JavaScript綜合知識     

動態語言沒有宣告式型別,想知道一個變數是什麼,得靠自己判斷。最直覺的 typeof 有幾個眾所皆知的坑(例如 typeof null 回傳 "object"),因此實務上常搭配 constructor 一起使用。

一、判斷陣列

<script type="text/javascript">
var a = [0];
document.write(isArray(a), '<br/>');
function isArray(obj){
  return (typeof obj == 'object') && obj.constructor == Array;
}
</script>

二、判斷字串

document.write(isString('test'), '<br/>');   // true
document.write(isString(10), '<br/>');       // false
function isString(str){
  return (typeof str == 'string') && str.constructor == String;
}

三、判斷數值

document.write(isNumber('test'), '<br/>');   // false
document.write(isNumber(10), '<br/>');       // true
function isNumber(obj){
  return (typeof obj == 'number') && obj.constructor == Number;
}

四、判斷日期

document.write(isDate(new Date()), '<br/>');  // true
document.write(isDate(10), '<br/>');           // false
function isDate(obj){
  return (typeof obj == 'object') && obj.constructor == Date;
}

五、判斷函式

document.write(isFunction(function test(){}), '<br/>');  // true
document.write(isFunction(10), '<br/>');                 // false
function isFunction(obj){
  return (typeof obj == 'function') && obj.constructor == Function;
}

六、判斷物件

document.write(isObject(new Object()), '<br/>');  // true
document.write(isObject(10), '<br/>');             // false
function isObject(obj){
  return (typeof obj == 'object') && obj.constructor == Object;
}

為什麼要兩個條件一起看

單用 typeof 有幾個已知盲點:typeof null 是 "object"、typeof [] 也是 "object"、typeof /regex/ 同樣是 "object"。加上 constructor 比對就能把這些情況區分開來。不過 constructor 也有弱點:如果物件是透過 Object.create(null) 建立的,它沒有 constructor,判斷時會出錯,所以三元的判斷式最好先確認 obj 不為 null。

現在的正解:Object.prototype.toString

更穩健的通用寫法如下,它能正確分辨陣列、日期、正則、null 等各種情況,也不受 constructor 被改寫的影響:

function typeOf(o){
  return Object.prototype.toString.call(o).slice(8, -1).toLowerCase();
}
typeOf([]);          // "array"
typeOf(new Date());  // "date"
typeOf(null);        // "null"
typeOf(/x/);         // "regexp"

另外,判斷陣列時現代瀏覽器已提供原生 Array.isArray(),它比 constructor 比對更可靠——特別是跨 iframe 時,不同 window 的 Array 建構子並不相同,用 constructor 會誤判,而 Array.isArray 不會。這個情境是當年那種寫法最容易翻車的地方。

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