動態語言沒有宣告式型別,想知道一個變數是什麼,得靠自己判斷。最直覺的 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。
更穩健的通用寫法如下,它能正確分辨陣列、日期、正則、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 不會。這個情境是當年那種寫法最容易翻車的地方。