怎么判断一个数据的类型
- 使用 typeof 关键字 [ 适用于基本数据类型]
- Object.prototype.toString.call() [适用于对象类型]
01 使用 typeof 关键字 [ 适用于基本数据类型]
var str = "我是字符串";
var num = 10;
var bool = true;
var func = function(){};
console.log(typeof str); //string
console.log(typeof num); //number
console.log(typeof bool); //boolean
console.log(typeof func); //function
02 当使用判断typeof对象类型的时候,呵呵了
var myArr = [1, 2, 3];
var myDate = new Date();
var obj = {};
console.log(typeof myArr); //object
console.log(typeof myDate); //object
console.log(typeof obj); //object
03 Object.prototype.toString.call() [适用于对象类型]
var myArr = [1, 2, 3];
var myDate = new Date();
var obj = {};
console.log(typeof myArr); //object
console.log(typeof myDate);//object
console.log(typeof obj); //object
console.log(Object.prototype.toString.call(myArr)); //[object Array]
console.log(Object.prototype.toString.call(myDate)); //[object Date]
console.log(Object.prototype.toString.call(obj)); //[object Object]
04 判断数组:Array.isArray() -> 注意兼容问题
var myArr = [1, 2, 3];
var obj = {};
console.log(Array.isArray(myArr)); //true
console.log(Array.isArray(obj)); //false