js数据类型有哪些
- 基本数据6种类型
- Number(数值)、String(字符串)、Boolean(布尔类型)、Null、undefined、symbol。
- 引用数据3种类型
- Object(对象)、array(数组)、function(函数)。
- es6中新增的2中数据结构
- set(类似于数组,本身是一个构造函数)、map(Object)
判断数据类型的4中方法
- typeof
typeof 1; //number
typeof ""; //string
typeof true; //boolean
typeof null; //object
typeof undefined; //undefined
typeof Symbol(); //symbol
typeof function(){}; //function
typeof {}; //object
typeof []; //object
typeof new Date(); //object
typeof new RegExp(); //object
typeof 判断基本数据类型的时候,除了typeof null; //object,其他情况都是正确的,typeof 判断基本引用数据类型的时候,除了function 返回function,其他返回的都是object,所以typeof无法判断引用具体类型
- instanceof 检测的是原型
console.log(Number(1).constructor) //ƒ Number() { [native code] }
console.log("".constructor) //ƒ String() { [native code] }
console.log(true.constructor) //ƒ Boolean() { [native code] }
console.log(null().constructor) // 报错
console.log(undefined().constructor) //报错
console.log(Symbol().constructor) //ƒ Symbol() { [native code] }
console.log({}.constructor) //ƒ Object() { [native code] }
console.log([].constructor) // ƒ Array() { [native code] }
console.log(function() {}.constructor) //ƒ Function() { [native code] }
- constructor 可以找到这个变量是通过谁构造出来的
console.log(Number(1).constructor) //ƒ Number() { [native code] }
console.log("".constructor) //ƒ String() { [native code] }
console.log(true.constructor) //ƒ Boolean() { [native code] }
console.log(null().constructor) // 报错
console.log(undefined().constructor) //报错
console.log(Symbol().constructor) //ƒ Symbol() { [native code] }
console.log({}.constructor) //ƒ Object() { [native code] }
console.log([].constructor) // ƒ Array() { [native code] }
console.log(function() {}.constructor) //ƒ Function() { [native code] }
- Object.prototype.toString.call() toString() 是 Object 的原型方法
Object.prototype.toString.call(Number(1)) //'[object Number]'
Object.prototype.toString.call('')//'[object String]'
Object.prototype.toString.call(null)//'[object null]'
Object.prototype.toString.call(undefined)//'[object undefined]'
Object.prototype.toString.call(Symbol())//'[object Symbol]'
Object.prototype.toString.call(true)//'[object Boolean]'
Object.prototype.toString.call({})//'[object Object]'
Object.prototype.toString.call([])//'[object Array]'
Object.prototype.toString.call(function() {})//'[object Function]'
Object.prototype.toString.call(new Date()) //'[object Date]'
Object.prototype.toString.call(new RegExp())//'[object RegExp]'