前文
在开始之前呢,我们需要搞清楚一个js的规则:
打印一个未声明的变量时,会报错
|
|
打印一个已声明变量的一个未定义属性时,不会报错,值为undefined
打印一个已声明未初始化变量的属性时,会报错
Undefined
Undefined就是已声明变量但还未初始化的一个值.
看这个例子
大家可能很好奇, 前文不是说了,打印未定义的变量会报错么?注意啦,这里是typeof age 而不是console.log(age)
这就很蛋疼了,已声明和未声明 用typeof 都是 undefined.但是有人可能问了,那这该怎么办呢?有没有什么办法能够分清楚已声明变量和未声明变量呢?
其实也是有办法的.我们对每个已声明变量都初始化.这样当typeof 操作符返回 “undefined” 时,我们就知道被检测的变量还没有被声明,而不是被初始化
总结一下什么情况下会 出现undefined:
- 已声明变量但还未初始化的变量
- 一个已声明变量的一个未定义属性
- typeof 一个已声明未初始化的变量
- typeof 一个未声明的变量
Null
高程上说 null是一个空对象指针,所以typeof null === ‘object’ 这条特殊的规则记住就好啦
由于undefined是由null派生而来12console.log(undefined == null) // trueconsole.log(undefined === null) // false
反正以后也是一直在用===所以这两个值还是不一样的
那么这个null该怎么用呢?前面我们说过,变量都要初始化,如果找不到合适的值那么就用null
|
|
总结
我们在声明变量的时候最好初始化为null,这样就可以排除未声明,已声明未定义的变量(或者一个变量的属性).