js数据类型判断有很多方法,这里我总结几种最为常见且有效的判断方法
一. typeof
1.基础数据类型
// String
let a = "zmb";
typeof a; // "string"
// Number
let a = 100;
typeof a; // "number"
// Boolean
let a = true;
typeof a; // "boolean"
// Undefined
let a;
typeof a; // "undefined"
// Null
let a = null;
typeof a; // "object";
引用类型
Object
let a = {};
typeof a; // "object"
Array
let a = [];
typeof a; // "object"
Function
let a = function(){};
typeof a; // "function"
Symbol
let a = Symbol(1);
typeof a; // "symbol"
总结: 对于基础类型String, Number, Boolean, Undefined, typeof可以准确的判断出数据类型;Null使用typeOf判断则为“object”
对于引用类型Object和Array使用typeof判断为“object”;Function和Symbol都可以准确的判断出数据类型
instanceof
用于检测引用类型
result = variable instanceof constructor;返回true/false;
alert(person instanceof Object); // 变量 person 是 Object 吗?
alert(colors instanceof Array); // 变量 colors 是 Array 吗?
alert(patterninstanceofRegExp); //变量pattern是RegExp吗?
a={};
a instanceof Object; // true
a instanceof Object; // true
b = [];
b instanceof Object; // true
b instanceof Array; //true
c = function() {};
c instanceof Object; // true
c instanceof Function; // true
根据规定,所有引用类型的值都是 Object 的实例。因此,在检测一个引用类型值和 Object 构造 函数时,instanceof 操作符始终会返回 true。当然,如果使用 instanceof 操作符检测基本类型的 值,则该操作符始终会返回 false,因为基本类型不是对象。
constructor属性
即判断对象的构造函数
注意:每个引用类型的constructor都是一个函数,即该对象的构造函数;只是是不同的构造函数,使用constructor就是检测构造函数的类型
"".constructor === String; // true
new Number(1).constructor === Number; //true
true.constructor === Boolean; // true
new Function().constructor = Function; // true
new Date().constructor == Date; // true
toString方法
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(new Function()); // "[object Function]"
Object.prototype.toString.call(new Date()); // "[object Date]"
Object.prototype.toString.call([]); // "[object Array]"
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 global]"