typeof 返回一个表示数据类型的字符串,返回结果包括symbol,string,number,boolean,undefined,function,object
typeof无法识别null,Array,Date,RegExp
console.log(typeof ''); //string
console.log(typeof 1); //number
console.log(typeof true); //boolean
console.log(typeof undefined); //undefined
console.log(typeof new Function()); //function
console.log(typeof {});//object
console.log(typeof null); //object
console.log(typeof []);//object
console.log(typeof new Date());//object
console.log(typeof new RegExp());//object
instanceof运算符测试一个对象在其原型链中是否存在一个构造函数的prototype属性
instanceof 不能检测null,undefined类型
var arr = [1];
console.log(arr instanceof Array); // true
console.log(arr instanceof Object); // true
function fn() {};
console.log(fn instanceof Function); // true
console.log(fn instanceof Object); // true
console.log(new Date() instanceof Date); // true
console.log(new RegExp() instanceof RegExp); // true
// 对于基本数据类型,字面量方式创建出来的结果和实例方式创建出来的是有一定区别的
console.log(new Number(1) instanceof Number); // true
console.log(1 instanceof Number); // false
console.log(new String('11') instanceof String); // true
console.log('11' instanceof String); // false
console.log(new Boolean(true) instanceof Boolean) // true
console.log(true instanceof Boolean) // false
constructor判断数据的构造函数类型
constructor无法判断null和undefined
console.log((1).constructor === Number); // true
console.log('11'.constructor === String); // true
console.log(true.constructor === Boolean); // true
console.log([1].constructor === Array); // true
console.log([1].constructor === Object); // false
console.log(new Function().constructor === Function) // true
console.log(new Function().constructor === Object) // false
console.log(/^a$/.constructor === RegExp); // true
console.log(new Date().constructor === Date); // true
console.log({}.constructor === Object) // true
// === 可以判断null,undefined
var a = null;
console.log(a === null); // true
var b = undefined;
console.log(b === undefined); // true
Object.prototype.toString.call()应用最为广泛
Object上的toString方法返回当前方法执行的主体所属类的详细信息,即[object Object].
console.log(Object.prototype.toString.call('')) // [object String]
console.log(Object.prototype.toString.call(1)) // [object Number]
console.log(Object.prototype.toString.call(true)) // [object Boolean]
console.log(Object.prototype.toString.call(null)) // [object Null]
console.log(Object.prototype.toString.call(undefined)) // [object Undefined]
console.log(Object.prototype.toString.call([])) // [object Array]
console.log(Object.prototype.toString.call(new Function())) // [object Function]
console.log(Object.prototype.toString.call({})) // [object Object]
console.log(Object.prototype.toString.call(new Date())) // [object Date]
console.log(Object.prototype.toString.call(new RegExp())) // [object RegExp]
console.log(Object.prototype.toString.call(new Error())) // [object Error]
以上就是数据检测的方法。