js的数据类型
在ECMAScript中有5中简单数据类型(基本数据类型) 分别是 Undefined, Null,Boolean,Number,String。在es6中引入了一个新基本数据类型是symbol。 还有复杂数据类型(引用类型) Object,本质上是由一组无序键值对组成的, Object, Array, function。
| 数据类型 | 说明 | 
| 数值类型Number | 只能是数字或者小数 | 
| 字符串类型String | 字符串类型String,用单引号或者双引号包裹的任何字符 | 
| 布尔类型Boolean | 只能是true或false代表真假 | 
| 未定义undefined | 定义变量后不赋值,这个变量就是undefined | 
| 空null,是对象类型 | null值表示一个空对象指针 | 
| 对象类型object | 有很多种,如数组对象、数学对象、日期对象 | 
| symbol | 用于表示一个独一无二的值,不能在调用Symbol时使用new关键字 | 
数据类型的判断
typeof
let obj = {name: '再见',age: 26}let fn = function () {console.log('我是 function 类型');}console.log(typeof 1);       //numberconsole.log(typeof 'abc');   //stringconsole.log(typeof true);    //booleanconsole.log(typeof undefined);  //undefined console.log(typeof fn);      //functionconsole.log(typeof (new Date));  //objectconsole.log(typeof null);     //objectconsole.log(typeof [1, 2, 3]);  //objectconsole.log(typeof obj);      //object
     由结果可知typeof可以测试出number、string、boolean、undefined及function
     优点:使用简单
     缺点:只能检测出除null外的基本数据类型和引用数据类型中functio
instanceof
let arr = [1, 2, 3, 4, 5, 6, 7]let obj = {name: '再兴',age: 26}let fn = function () {console.log('我是 function 类型');}console.log(arr instanceof Array);  //trueconsole.log(obj instanceof Object);  //trueconsole.log(fn instanceof Function);  //trueconsole.log((new Date) instanceof Date);  //true
     优点:能检测出引用类型的数据
     缺点:不能检测出基本类型且不能跨iframe
Object.prototype.toString.call
let obj = {name: '小红',age: 21}let fn = function () {console.log('我是 function 类型');}console.log(Object.prototype.toString.call(1));        // [object Number]console.log(Object.prototype.toString.call('Hello tomorrow')); // [object String ]console.log(Object.prototype.toString.call(true));     // [object Boolean]console.log(Object.prototype.toString.call(undefined));  // [object Undefined]console.log(Object.prototype.toString.call(fn));   // [object Function]console.log(Object.prototype.toString.call(new Date));  // [object Date]console.log(Object.prototype.toString.call(null));   // [object Null]console.log(Object.prototype.toString.call([1, 2, 3]));  // [object Array]console.log(Object.prototype.toString.call(obj));       // [object Object]
     优点:能检测出所有的类型
     缺点:ie6 下,undefined 和 null 均为object
constructor
  let arr = [1, 2, 3, 4, 5, 6, 7]let obj = {name: '狗狗',age: 28}let fn = function () {console.log('我是 function 类型');}console.log((9).constructor === Number);  //trueconsole.log('hello'.constructor === String);  //trueconsole.log(true.constructor === Boolean);  //trueconsole.log(fn.constructor === Function);  //trueconsole.log((new Date).constructor === Date);  //trueconsole.log(obj.constructor === Object);  //trueconsole.log([1, 2, 3].constructor === Array);  //true
     【注意】:constructor不能判断undefined和null,并且使用它是不安全的,因为contructor的指向是可以改变的
     优点:基本能检测所有的类型(除了null 和 undefined)
     缺点:contructor 易被修改,也不能跨iframe