这是我参与更文挑战的第10天,活动详情查看: 更文挑战
undefined类型只有一个值,那就是undefined
undefined
类型只有一个值,就是特殊值undefined
,比如我们在定义一个变量没有指定初始值的时候,那这个变量的默认值就会是undefined
,比如
var a // undefined
let a // undefined
复制代码
需要注意的是,const
定义的变量不支持省略初始值,如果用const
声明变量时没有指定初始值,那么将会报错而不是默认为undefined
,但是我们仍然可以显式的将一个变量初始化为undefined
const b // Uncaught SyntaxError: Missing initializer in const declaration
const b = undefined // undefined
复制代码
对于声明变量这块感兴趣的可以看我以前文章【青山学js】var let const有什么区别?什么是变量提升?
undefined
的意思是找不到,一个未定义的变量也找不到,但是一个被经过声明的变量,即使值为undefined,它和一个没有定义过的变量也是不一样的。
let abc
console.log(abc) // undefined
console.log(bcd) // VM448:1 Uncaught ReferenceError: bcd is not defined
复制代码
对于未声明的变量,只能进行一个操作,那就是typeOf
typeof bcd // undefined
复制代码
undefinde的几种情况
声明但未初始化的变量
let abc // undefined
复制代码
对象中不存在的属性
let obj = {}
obj.title // undefined
复制代码
函数需要实参,但是调用时没有传值,形参是undefined
function showName(name) {
console.log(name)
}
showName() // name
复制代码
函数调用没有返回值或者return后没有数据,接收函数返回的变量是undefined
function getName() {
console.log('hello world')
}
let name = getName()
console.log(name) // undefined
复制代码
Null
和undefined
相似,Null
类型也只有一个值,就是特殊值null
,逻辑上讲,null
值表示一个空对象指针,这也是给typeof
传入一个null
会返回一个Object
的原因
let hello = null
typeof hello // "object"
复制代码
不过null并不是一个实际意义上的对象,因为它完全是空的,并不拥有object原型链上的方法
null instanceof Object // false
复制代码
null
值的意思就是空,所以我们常常在定义一个对象时赋值为null
而不是undefined
,因为这样更符合语义化,因为经过声明的值就不再是‘找不到’,只能是‘空’
不过有趣的是,undefined的值是又null派生出来的,因此js将他们表面上视为相等,不过他们并不全等
null == undefined // true
null === undefined // false
复制代码
所以如果我们想判断一个值是否为undefined
的时候,不应该直接与undefined
比较,因为它也可能是null
let abc = null
if (abc == undefined) console.log('找不到')
// 找不到
复制代码
如果我们要判断一个值是否找不到时,应尽量使用typeof
,同样,我们也不应该直接用上面的方法判断一个值是否为null
,因为它可能是undefined