基本数据类型
JavaScript常见的基本数据类型有5种,分别是
- Boolean 布尔型
- Number 数字型
- String 字符串型
- Undefined 未定义型
- Null 空类型
引用数据类型
- object 对象
- array 数组
- function 函数 ......
Null 和 Undefined 的区别
Null
Null 意为空值,表示一个对象被重置为空对象 也就是说,这个值虽然定义了,但是没有指向任何对象
Undefined
Undefined 意为为定义的值,表示一个变量的初始状态
在看这两者的区别前,不妨先看看它们的相同点
首先,它们都用以描述空值,都代表“空”,且它们的值相等
console.log( undefined == null ) //true
其次,当把它们转换为布尔值时,都是 false
console.log( Boolean(undefined) ) //false
console.log( Boolean(null) ) //false
这样看来这两者似乎没有什么区别,但实际上当你使用 typeof 打印出来看就会发现,它们的类型不一样
console.log(typeof (null)) //object
console.log(typeof (undefined)) //undefined
console.log(null===undefined) //false
而且当把它们转换成数据类型时,它们的值也不一样
console.log(Number(null)) //0
console.log(Number(undefined)) //NaN
讲完了区别,再来看看 undefined 的一些经常出现的场景
1.声明了变量但没有赋值
let gkd
console.log(gkd) //undefined
2.定义了形参,但没有传递实参
function fn(gkd) {
console.log(gkd) //undefined
}
fn()
3.对象属性不存在
console.log (Object.gkd) // undefined
4.对象没有赋值的属性
console.log(.a) // undefined