之前没太注意is not defined和undefined有什么区别,每次都是简单的把两者理解为未定义,现在回过头来梳理js基础的时候才发现其中区别还是很鲜明的。 先从单纯的字面意思来理解一下(有道词典):
is not defined: 未定义 not defined: 未定义,没有定义,无法定义
&&
undefined: 不明确的 单从字面意思大体也能看出两者的区别:前者是没有定义,也就是说没有;后者是不明确的,也就是说不知道有没有定义. not defined 看demo1:
12 | console.log(a) // 报错:a is not defined 终止运行 |
---|
一个未定义 的变量是没有声明的变量,这样的变量在使用时会直接报错误。
demo2:
123 | var aconsole.log(a) // 未报错,提示: undefined |
---|
demo3:
1234 | var p = 1p = undefinedconsole.log(p) // 未报错,提示: undefined |
---|
demo4:
12 | console.log(window.a)// 未报错,提示: undefined |
---|
demo5:
123 | var a = []console.log(a.b)// 未报错,提示: undefined |
---|
demo6:
123 | var a = {}console.log(a.b)// 未报错,提示: undefined |
---|
demo7:
123 | function f() {console.log(1)}console.log(f())// 未报错,提示: undefined |
---|
有一点需要注意的是not defined 和 undefined 的typeof()的值都为”undefined”,所以无法用typeof()来判断这两者。
demo8:
12 | !undefined ? console.log('undefined is false') : console.log('undefined is not false')// undefined is false |
---|
demo9:
12 | !null? console.log('null is false') : console.log('null is not false')// null is false |
---|
虽然null和undefined基本是同义的,但是在用法上还是有一些细微的差别的
null表示“没有对象”,即此处不该有值
如上文demo2-demo7 部分