返回数据类型的函数封装
回顾typeof方法
typeof操作符可以确定任意变量的数据类型,可以返回的值有
- number
- string
- boolean
- object
- undefined
- function
- symbol
泛泛的引用值和null,会返回object;
typeof的两种写法:
typeof(data)
typeof data
注意typeof返回的值是字符串。
函数封装
由于typeof()
方法只能返回上述7种数据类型,若想更具体的返回数据类型,比如null,数组,包装类等,则需要借助Object.prototype.toString.call()
的方法来扩充功能。
var template = {
"[object Object]" : "object",
"[object Array]" : "array",
"[object Number]" : "number - object",
"[object String]" : "string - object",
"[object Boolean]" : "boolean - object",
"[object Null]" : "null"
};
function type(target) {
if(typeof(target) == "object") {
var str = Object.prototype.toString.call(target);
return template[str];
} else {
return typeof(target);
}
}