本文共 1109 字,大约阅读时间需要 3 分钟。
Let’s talk about the similarities first.
让我们先谈一下相似之处。
null
and undefined
are JavaScript primitive types.
null
和undefined
是JavaScript基本类型。
The meaning of undefined
is to say that a variable has declared, but it has no value assigned.
undefined
的意思是说已经声明了一个变量,但是没有赋值。
let age //age is undefined
let age = null //age is null
Note: accessing a variable that’s not been declared will raise a
ReferenceError: <variable> is not defined
error, but this does not mean it’sundefined
.注意:访问未声明的变量将引发
ReferenceError: <variable> is not defined
错误,但这并不意味着undefined
。
How do you check if a variable is null? Use the comparison operator, for example age === null
如何检查变量是否为空? 使用比较运算符,例如age === null
Same for undefined: age === undefined
与未定义相同: age === undefined
In both cases, you can check for:
在这两种情况下,您都可以检查:
if ( ! age ) {}
and this will be matching both null
and undefined
.
这将匹配null
和undefined
。
You can also use the typeof
operator:
您还可以使用typeof
运算符:
let agetypeof age //'undefined'
although null
is evaluated as an object, even though it is a primitive type:
尽管null
被评估为一个对象,即使它是原始类型:
let age = nulltypeof age //'object'
翻译自:
转载地址:http://vmmgb.baihongyu.com/