判断数据类型的方法

250 阅读1分钟

1、typeof

基本数据类型中null返回object无效,其他均有效;引用数据类型function有效其他返回object均无效。

typeof "a"; // string 有效
typeof 1; // number 有效
typeof true; //boolean 有效
typeof Symbol(); // symbol 有效
typeof undefined; //undefined 有效
typeof new Function(); // function 有效
typeof null; //object 无效
typeof [1]; //object 无效
typeof new RegExp(); //object 无效
typeof new Date(); //object 无效

2、instanceof

instanceof是查找原型链上是否有该对象,所以不能用object查,因为所有的对象原型链上都有object

[] instanceof Array; // true
new Date() instanceof Date; // true
function Person() {}
new Person() instanceof Person; //true
[] instanceof Object; // true
new Date() instanceof Object; // true
new Person() instanceof Object; // true

3、constructor

通过构造函数查类型,所以undefinednull无效

"a".constructor === String; // true
(1).constructor === Number; // true
new Number(1).constructor === Number; // true
true.constructor === Boolean; // true
(() => {}).constructor === Function; // true
new Function().constructor === Function; // true
new Date().constructor === Date; // true
[].constructor === Array; // true
Symbol().constructor === Symbol; // true

4、toString

toString() 是 Object 的原型方法,调用该方法,默认返回当前对象的Class。

Reflect属于es6内容。将Object对象的一些明显属于语言内部的方法(比如Object.defineProperty),放到Reflect对象上。现阶段,某些方法同时在ObjectReflect对象上部署,未来的新方法将只部署在Reflect对象上。也就是说,从Reflect对象上可以拿到语言内部的方法。

Reflect.toString.call(""); // [object String]
Reflect.toString.call(1); // [object Number]
Reflect.toString.call(true); // [object Boolean]
Reflect.toString.call(Symbol()); //[object Symbol]
Reflect.toString.call(undefined); // [object Undefined]
Reflect.toString.call(null); // [object Null]
Reflect.toString.call(new Function()); // [object Function]
Reflect.toString.call(new Date()); // [object Date]
Reflect.toString.call([]); // [object Array]
Reflect.toString.call(new RegExp()); // [object RegExp]
Reflect.toString.call(new Error()); // [object Error]
Reflect.toString.call(document); // [object HTMLDocument]
Reflect.toString.call(window); //[object global] window 是全局对象 global 的引用
Reflect.toString.call(new RegExp()); // [object RegExp]

参考学习

javascript怎么判断数据类型