一、分类(2大类)
1. 基本(值)类型
- Number: 任意数值
- String: 任意文本
- Boolean: true / false
- undefined: undefined
- null: null
2. 对象(引用)类型
- Object: 任意对象
var obj ={}
- Function: 特别的对象类型(可执行)
function test(){
var a = 3;
}
- Array: 特别的对象类型(根据数值下标操作,内部数据有序)
var arr = [3,'abc']
console.log(arr[1]); //abc
二、判断
- typeof:返回的是数据类型的字符串表达形式
- 可以区别:数值, 字符串, 布尔值, undefined, function
- 不能区别:null与对象, 一般对象与数组
- ===
- 可以判断:undefined 和 null
//1. 基本类型
// typeof: 返回的是数据类型的字符串表达形式
var a
console.log(a, typeof a, typeof a==='undefined',a===undefined) // undefined 'undefined' true true
console.log(undefined==='undefined'); // false
a = 3
console.log(typeof a === 'number')//true
a = 'atguigu'
console.log(typeof a === 'string')//true
a = true
console.log(typeof a === 'boolean')//true
a = null
console.log(a===null) // true
console.log(typeof a) // 'object' 故:不能区别: null与对象
- instanceof
- 专门用来判断对象数据的类型: Object,Array与Function
//2. 对象类型
var b1 = {
b2: [2, 'abc', console.log],
b3: function () {
console.log('b3')
}
}
//b1 instanceof Object 意思是:判断 b1 是不是 Object 的实例
console.log(b1 instanceof Object, b1 instanceof Array, typeof b1) // true false 'object'
console.log(b1.b2 instanceof Array, b1.b2 instanceof Object, typeof b1.b2) // true true 'object'
console.log(b1.b3 instanceof Function, b1.b3 instanceof Object, typeof b1.b3) // true true 'function'
//typeof 可以区别 function ,不能区别 object 和 数组
console.log(typeof b1.b2[2]) // 'function'
console.log(typeof b1.b2, '-------') // 'object'
console.log(typeof b1.b3==='function') // true
console.log(typeof b1.b2[2]==='function') // true
b1.b2[2](3); //3
b1.b3(); //b3
var b1 = {
b2: [2, 'abc', console.log],
b3: function () {
console.log('b3') //b3
return function () {
return 'xxx'
}
}
}
b1.b2[2](3); //3
b1.b3(); //b3
console.log(b1.b3()()); //xxx
三、undefined 与 null 的区别
- undefined代表没有赋值
- null代表赋值了, 只是值为null
var a
console.log(a) // undefined
a = null
console.log(a) // null
四、什么时候给变量赋值为 null
- 初始赋值,表明将要赋值为对象,var a = null ,a将指向一个对象,但对象此时还没有确定。
- 结束前,让对象成为垃圾对象(被垃圾回收器回收) ,a = null 。
//起始
var b = null // 初始赋值为null, 表明将要赋值为对象
//确定对象就赋值
b = ['atguigu', 12]
//最后
b = null // 让b指向的对象成为垃圾对象(被垃圾回收器回收)
五、严格区别变量类型与数据类型
js的变量本身是没有类型的, 变量的类型实际上是变量内存中数据的类型。
- 变量类型(变量内存值的类型):
- 基本类型: 保存基本类型数据
- 引用类型: 保存对象地址值
- 数据对象
- 基本类型
- 对象类型