javascript断数据类型
javascript数据类型分为基本数据类型和引用数据类型。其中基本数据类型包括Undefined、Null、Boolean、Number、String、Symbol (ES6新增,表示独一无二的值),而引用数据类型统称为Object对象,主要包括对象、数组和函数。
1.typeoftypeof返回一个表示数据类型的字符串,返回结果包括:number、boolean、string、symbol、object、undefined、function等7种数据类型,但不能判断null、array等。
console.log(typeof Symbol()); // symbol 有效 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 null); //object 无效 console.log(typeof []); //object 无效 console.log(typeof new Date()); //object 无效 console.log(typeof new RegExp()); //object 无效
instanceof 是用来判断A是否为B的实例,表达式为:A instanceof B,如果A是B的实例,则返回true,否则返回false。instanceof 运算符用来测试一个对象在其原型链中是否存在一个构造函数的 prototype 属性,但它不能检测null 和 undefined。
console.log([] instanceof Array); //true console.log({} instanceof Object);//true console.log(new Date() instanceof Date);//true console.log(new RegExp() instanceof RegExp)//true console.log(null instanceof Null)//报错 console.log(undefined instanceof undefined)//报错
3.严格运算符===
只能用于判断null和undefined,因为这两种类型的值都是唯一的。
4.constructor
constructor作用和instanceof非常相似。但constructor检测 Object与instanceof不一样,还可以处理基本数据类型的检测。不过函数的 constructor 是不稳定的,这个主要体现在把类的原型进行重写,在重写的过程中很有可能出现把之前的constructor给覆盖了,这样检测出来的结果就是不准确的。
5.Object.prototype.toString.call()
Object.prototype.toString.call() 是最准确最常用的方式。
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(undefined) ) ; // [object Undefined]
console.log( Object.prototype.toString.call(null) ) ; // [object Null]
console.log( Object.prototype.toString.call(new Function()) ) ; // [object Function]
console.log( Object.prototype.toString.call(new Date()) ) ; // [object Date]
console.log( Object.prototype.toString.call([]) ) ; // [object Array]
console.log( Object.prototype.toString.call(new RegExp()) ) ; // [object RegExp]
console.log( Object.prototype.toString.call(new Error()) ) ; // [object Error]

浙公网安备 33010602011771号