1. 分类
- 基本(值)类型
- String:任意字符串
- Number:任意的数字
- Boolean:true / false
- undefined:undefined
- null:null
- 对象(引用)类型
- Object:任意对象
- Function:一种特别的对象(可以执行)
- Array:一种特别的对象(有数值下标,通过数值下标进行操作,内部数据是有序的)
2. 判断
- typeof – 返回数据类型的字符串表达(小写)
- 可以判断:undefined / 数值 / 字符串 / 布尔值 / function
- 不能判断 null 与 object object 和 array
- instanceof – 判断对象的具体类型
- ===
- 可以判断:undefined / null
注意要区分 undefined 和 ‘undefined’
- 基本数据类型判断示例
var a ;
console.log(a,typeof a,typeof a==='undefined',a===undefined)
// undefined undefined true true
console.log(undefined==='undefined')
// false
a = 4
console.log(typeof a==='number') // true
a = 'atguigu'
console.log(typeof a==='string') // true
a = true
console.log(typeof a==='boolean')
a = null
console.log(typeof a,a===null) // 'object' true
- 对象数据类型判断示例
var b1 = {
b2:[1,'abc',console.log],
b3:function (){
console.log('b3')
}
console.log(b1 instanceof Object,b1 instanceof Array) // true false
console.log(b1.b2 instanceof Array,b1.b2 instanceof Object) // true true
console.log(b1.b3 instanceof Function,b1.b3 instanceof Object) // true true
console.log(typeof b1.b3 === 'function') // true
3. 关于数据类型的问题
(1) undefined 与 null 的区别
undefined – 声明未赋值;
null – 定义并赋值了,只是值为null
var a;
console.log(a) //undefined
a = null
console.log(a) //null
(2) 什么时候给变量赋值为null
- 初始赋值 表明变量要复制为对象
- 结束时,让对象成为垃圾对象(被垃圾回收机制回收)
// 起始
var b = nul1 // 初始赋值为muLL,表明将要赋值为对象
// 确定对象就赋值
b = ['atguigu',12]
// 最后
b = null // 让b指向的对象成为垃圾对象(被垃圾回收器回收)
// b=2
(3) 严格区分变量类型和数据类型
- 数据类型
- 基本类型
- 对象类型
- 变量类型(变量内存值的类型)
- 基本类型:保存的就是基本数据类型的数据
- 引用类型 :保存的是地址值