出處
Object 對象 - JavaScript 教程 - 網道 ---- tostring-的應用:判斷數據類型
代碼
- 不同數據類型的
Object.prototype.toString
方法返回值如下
- 數值:返回
[object Number]
宅荤。
- 字符串:返回
[object String]
弧烤。
- 布爾值:返回
[object Boolean]
璃搜。
-
undefined
:返回[object Undefined]
。
-
null
:返回[object Null]
食拜。
- 數組:返回
[object Array]
。
-
arguments
對象:返回[object Arguments]
眯杏。
- 函數:返回
[object Function]
匾乓。
-
Error
對象:返回[object Error]
。
-
Date
對象:返回[object Date]
鳄厌。
-
RegExp
對象:返回[object RegExp]
荞胡。
- 其他對象:返回
[object Object]
。
Object.prototype.toString.call(2) // "[object Number]"
Object.prototype.toString.call('') // "[object String]"
Object.prototype.toString.call(true) // "[object Boolean]"
Object.prototype.toString.call(undefined) // "[object Undefined]"
Object.prototype.toString.call(null) // "[object Null]"
Object.prototype.toString.call(Math) // "[object Math]"
Object.prototype.toString.call({}) // "[object Object]"
Object.prototype.toString.call([]) // "[object Array]"
- 利用這個特性了嚎,可以寫出一個比
typeof
運算符更準確的類型判斷函數泪漂。
var type = function (o){
var s = Object.prototype.toString.call(o);
return s.match(/\[object (.*?)\]/)[1].toLowerCase();
};
type({}); // "object"
type([]); // "array"
type(5); // "number"
type(null); // "null"
type(); // "undefined"
type(/abcd/); // "regex"
type(new Date()); // "date"
- 在上面這個
type
函數的基礎上,還可以加上專門判斷某種類型數據的方法歪泳。
var type = function (o){
var s = Object.prototype.toString.call(o);
return s.match(/\[object (.*?)\]/)[1].toLowerCase();
};
['Null',
'Undefined',
'Object',
'Array',
'String',
'Number',
'Boolean',
'Function',
'RegExp'
].forEach(function (t) {
type['is' + t] = function (o) {
return type(o) === t.toLowerCase();
};
});
type.isObject({}) // true
type.isNumber(NaN) // true
type.isRegExp(/abc/) // true