undefined与null的区别
- undefined代表定义未赋值
- null代表定义并且赋值了,值为null
什么时候给变量赋值为null呢
- 初始赋值,表明将要赋值为对象
- 结束前,让对象成为垃圾对象(被垃圾回收器回收)
严格区分变量类型与数据类型
- 数据的类型
- 基本类型
- String:任意字符串
- Number:任意数字
- Boolean:true/false
- Undefined:undefined
- Null:null
- 对象类型
- Object:任意对象
- Function:一种特别的对象(可以执行)
- Array:一种特别的对象(数值下标,内部数据是有序的)
- ……
- 基本类型
- 变量的类型
- 基本类型:保存的是基本类型的数据
- 引用类型:保存的是地址值,数据类型是对象类型
判断
-
typeof
可以判断:undefined/数值/字符串/布尔值/function
不能判断:null与object,object与array
对于基本数据类型,返回其本身的数据类型,对于函数返回function,其它对象均返回object
let a; console.log(typeof a) // undefined a = "123"; console.log(typeof a); // string a = 1; console.log(typeof a) // number a = true; console.log(typeof a) // boolean a = null; console.log(typeof a) // object
-
instanceof
判断对象的具体数据类型
let a = new Date() console.log(a instanceof Date) // true let b = {} console.log(b instanceof Object) // true let c = [] console.log(c instanceof Array) // true
-
===
可以判断:undefined,null
let c; console.log(c === undefined) // true c = null; console.log(c === null) // true
-
Object.prototype.toString()
可以判断所有数据类型
let d; console.log(Object.prototype.toString.call(d)) // [object Undefined] d = ""; console.log(Object.prototype.toString.call(d)) // [object String] d = 123; console.log(Object.prototype.toString.call(d)) // [object Number] d = true; console.log(Object.prototype.toString.call(d)) // [object Boolean] d = null; console.log(Object.prototype.toString.call(d)) // [object Null] d = {}; console.log(Object.prototype.toString.call(d)) // [object Object] d = function(){} console.log(Object.prototype.toString.call(d)) // [object Function] d = []; console.log(Object.prototype.toString.call(d)) // [object Array] d = new Date(); console.log(Object.prototype.toString.call(d)) // [object Date] d = new RegExp("123", "i"); console.log(Object.prototype.toString.call(d)) // [object RegExp]