js 数据类型检查
JavaScript 有三种方法,可以确定一个值到底是什么类型。
- typeof 运算符
- instanceof 运算符
- Object.prototype.toString方法
typeof 运算符
像null array {}都是object 不能区分
从上面typeog undefined ==undefined
typeof可以用来检查一个没有声明的变量,而不报错。
// 变量v没有用var命令声明,直接使用就会报错。但是,放在typeof后面,就不报错了
//在不清楚某个变量是否存在时 可以用typeof 做一层防错处理
// 错误的写法
if (v) {
// ...
}
// ReferenceError: v is not defined
// 正确的写法
if (typeof v === "undefined") {
// ...
}
instanceof 运算符
instanceof 运算符用于检测构造函数的 prototype上的
constructor 属性是否出现在某个实例对象的原型链上。
!!!注意的是 原型上constructor 是可以修改的
instanceof 可以检测复杂数据类型 基础类型无法检测 返回的都是false
//console.log(null instanceof Null);
//console.log(undefined instanceof Undefined);
null 跟 undefined 直接输出会报错 但是使用new 关键字创建就不会
- constructor
Object.prototype.toString方法 (最终解决办法)
Object.prototype.toString.call("1") // {object String}
Object.prototype.toString.call(1) // {object Number}
Object.prototype.toString.call(null) // {object Null}
Object.prototype.toString.call(undefined) // {object Undefined}
Object.prototype.toString.call(true) // {object Boolean}
Object.prototype.toString.call({}) // {object Object}
Object.prototype.toString.call([]) // {object Array}
Object.prototype.toString.call(function () {}) // {object Fuction}
tostring的封装
function getType(obj) {
//tostring 会返回对应不同的标签的构造函数
var toString = Object.prototype.toString;
var map = {
'[object Boolean]': 'boolean',
'[object Number]': 'number',
'[object String]': 'string',
'[object Function]': 'function',
'[object Array]': 'array',
'[object Date]': 'date',
'[object RegExp]': 'regExp',
'[object Undefined]': 'undefined',
'[object Null]': 'null',
'[object Object]': 'object'
};
if (obj instanceof Element) {
return 'element';
}
return map[toString.call(obj)];
}
//或者
function classof(o){
if(o === null) return "Null";
if(o === undefined) return "Undefined";
//Object.prototype.toString()返回"[object Object]",然后call(o)参数,
//返回该类型,如number类型call(1),返回"[object Number]",再使用slice(截取类型部分)
return Object.prototype.toString.call(o).slice(8,-1);
}