基本数据类型:字符串类型(string)、数值类型(number)(非数值NaN)、布尔类型(boolean)、未定义类型(undefined)、空类型(null)、symbol类型(ES6)。
引用数据类型:对象类型(object)。
1、获取数据类型
(1)typeof
console.log(typeof "hu");//打印结果:string
console.log(typeof 20);//打印结果:number
console.log(typeof true);//打印结果:boolean
console.log(typeof undefined);//打印结果:undefined
console.log(typeof null);//打印结果:object
console.log(typeof { age: 20 });//打印结果:object
console.log(typeof function(){});//打印结果:function
(2)instanceof 需要指定要判断的数据类型,反回布尔值(true or false),用来判断对象(object)是否为一个类。
let arr = [1,2,3];
let obj = { age:20 };
console.log(arr instanceof Array);//打印结果:true
console.log(arr instanceof Object);//打印结果:true,因为数组属于 object 类型派生出来的一种特殊类型。
console.log(obj instanceof Array);//打印结果:false
console.log(obj instanceof Object);//打印结果:true
(3)Object.prototype.toString.call() 原型方法。
console.log(Object.prototype.toString.call(null));//打印结果:[object Null]
console.log(Object.prototype.toString.call(undefined)); //打印结果:[object Undefined]
console.log(Object.prototype.toString.call(true)); //打印结果:[object Boolean]
console.log(Object.prototype.toString.call('hu'));//打印结果:[object String]
console.log(Object.prototype.toString.call(20));//打印结果:[object Number]
console.log(Object.prototype.toString.call(function(){}));//打印结果:[object Function]
console.log(Object.prototype.toString.call([1,2,3]));//打印结果:[object Array]
console.log(Object.prototype.toString.call({age:20}));//打印结果:[object Object]
console.log(Object.prototype.toString.call(new Date));//打印结果:[object Date]
2、类型转换
(1)字符串类型转换,除空类型(null)和未定义类型(undefined)外每种数据类型都具有一个toString()对象方法。
let num = 20;
let bool = true;
consolse.log(typeof num.toString());//打印结果:string
consolse.log(typeof bool.toString());//打印结果:string
(2)数值类型转换,Number()、parseInt()、parseFloat()。
| 参数类型 | 参 数 值 | 转 换 | ||
|---|---|---|---|---|
| boolean | true | false | 1 | 0 |
| number | 值 | 返回相同的值 | ||
| null | null | 0 | ||
| undefined | undefined | NaN | ||
| string | 只包含数字 | 返回对应数值 | ||
| 包含有效的浮点数 | 返回对应浮点数 | |||
| 包含有效的十六进制数 | 将十六进制数转换为十进制数并返回 | |||
| 包含有效的八进制数 | 将八进制数转换为十进制数并返回 | |||
| 字符串为空 | 0 | |||
| 除以上格式外 | NaN | |||
| object | 一般为 NaN |
(3)布尔类型转换,Boolean()。
| 数据类型 | 转换为 true | 转换为 false |
|---|---|---|
| number | 非零数字 | 0 和 NaN |
| string | 非空字符串 | 空字符串 |
| boolean | true | false |
| null | 无 | 永远转换为 false |
| undefined | 无 | |
| object | 任何对象(包括空对象) | null |