使用typeof判断数据类型
使用方法:
typeof(123); // number
typeof('123'); // string
typeof({}); // object
typeof([]); // object
主要用于检测基本数据类型
优点:
代码量少,区分基本的数据类型
缺点:
引用类型无法区分,全部表示为object
基本数据类型:Number, String, Boolean, Null, undefined, object, symbol, bigInt
引用数据类型:function, Array, Date
使用instanceof判断数据类型
使用方法
console.log(123 instanceof Object); // false
consolse.log(new Number(123) instanceof Number); // true
consolse.log([] instanceof Array); // true
返回值为true、false,主要用于判断引用类型
优点:
可以用来检测引用类型
缺点:
检测基本数据类型较麻烦,需要准确对应相应的数据类型,否则无法正确检测
使用Object.prototype.toString.call判断数据类型
优点:
可以检测出所有数据类型
缺点:
代码过长
console.log(Object.prototype.toString.call({})); //[object Object]
console.log(Object.prototype.toString.call([])); //[object Array]
console.log(Object.prototype.toString.call(false)); //[object Boolean]
console.log(Object.prototype.toString.call(null)); //[object Null]
console.log(Object.prototype.toString.call('1123')); //[object String]
console.log(Object.prototype.toString.call(Symbol()));//[object Symbol]
console.log(Object.prototype.toString.call(new Date)); //[object Date]