toString
方法的主要用途是返回對象的字符串形式焚辅,除此之外州胳,還有一個重要的作用,就是判斷一個值的類型芳杏。
var o = {};
o.toString(); // "[object Object]"
上面代碼調(diào)用空對象的 toString
方法,結(jié)果返回一個字符串 object Object
辟宗,其中第二個 Object
表示該值的準確類型爵赵。這是一個十分有用的判斷數(shù)據(jù)類型的方法。
實例對象的 toString
方法泊脐,實際上是調(diào)用 Object.prototype.toString
方法空幻。使用 call
方法,可以在任意值上調(diào)用 Object.prototype.toString
方法容客,從而幫助我們判斷這個值的類型秕铛。不同數(shù)據(jù)類型的 toString
方法返回值如下:
數(shù)值:返回
[object Number]
则剃。
字符串:返回[object String]
。
布爾值:返回[object Boolean]
如捅。
undefined:返回[object Undefined]
棍现。
null:返回[object Null]
。
數(shù)組:返回[object Array]
镜遣。
arguments對象:返回[object Arguments]
己肮。
函數(shù):返回[object Function]
。
Error對象:返回[object Error]
悲关。
Date對象:返回[object Date]
谎僻。
RegExp對象:返回[object RegExp]
。
其他對象:返回[object " + 構(gòu)造函數(shù)的名稱 + "]
寓辱。
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
運算符更準確的類型判斷函數(shù)。
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
函數(shù)的基礎(chǔ)上秫筏,還可以加上專門判斷某種類型數(shù)據(jù)的方法诱鞠。
['Null',
'Undefined',
'Object',
'Array',
'String',
'Number',
'Boolean',
'Function',
'RegExp',
'NaN',
'Infinite'
].forEach(function (t) {
type['is' + t] = function (o) {
return type(o) === t.toLowerCase();
};
});
type.isObject({}) // true
type.isNumber(NaN) // true
type.isRegExp(/abc/) // true