JS 判断数据类型方法
基本类型:
String
Number
Boolean
Symbol
Undefined
Null
引用类型:Object
Array
Date
Function
RegExp
方法 1(推荐):toString
// 对于 Object 对象,直接调用 toString() 就能返回 [object Object]
new Object().toString(); // [object Object]
// 而对于其他对象,则需要通过 call / apply 来调用才能返回正确的类型信息
Object.prototype.toString.call(''); // [object String]
Object.prototype.toString.call(1); // [object Number]
Object.prototype.toString.call(true); // [object Boolean]
Object.prototype.toString.call(Symbol()); // [object Symbol]
Object.prototype.toString.call(undefined); // [object Undefined]
Object.prototype.toString.call(null); // [object Null]
Object.prototype.toString.call({}); // [object Object]
Object.prototype.toString.call([]); // [object Array]
Object.prototype.toString.call(new Date()); // [object Date]
Object.prototype.toString.call(new Function()); // [object Function]
Object.prototype.toString.call(new RegExp()); // [object RegExp]
Object.prototype.toString.call(new Error()); // [object Error]
Object.prototype.toString.call(document); // [object HTMLDocument]
Object.prototype.toString.call(window); // [object Window]
方法 2: typeof
- 只能区分部分类型.
// 可区分开的类型
typeof ''; // string
typeof 1; // number
typeof true; // boolean
typeof Symbol(); // symbol
typeof undefined; // undefined
typeof {}; // object
typeof new Function(); // function
// 无法区分
typeof null; // object
typeof []; // object
typeof new Date(); // object
typeof new RegExp(); // object
方法 3:constructor
- 只能区分部分类型
''.constructor === String; // true
new Number(1).constructor === Number; // true
true.constructor === Boolean; // true
new Object().constructor === Object; // true
[].constructor === Array; // true
new Date().constructor === Date; // true
new Function().constructor === Function; // true
// `null` 和 `undefined` 是无效的对象,因此是不会有 `constructor` 存在的
// 函数的 `constructor` 是不稳定的,这个主要体现在自定义对象上,当重写 `prototype` 后,原有的 `constructor` 引用会丢失,会默认为 `Object`
方法 4: instanceof
- 只能用来判断两个对象是否属于实例关系, 而不能判断一个对象实例具体属于哪种类型。
{} instanceof Object; // true
// 无法区分
[] instanceof Array; // true
[] instanceof Object; // true
// 无法区分
new Date() instanceof Date; // true
new Date() instanceof Object; // true
// 无法区分
new Function() instanceof Function; // true
new Function() instanceof Object; // true