在理解undefined
和null
之间的差异之前,我们先来看看它们的相似类。
它们属于 JavaScript 的 7 种基本类型。
let primitiveTypes =
['string','number','null','undefined','boolean','symbol', 'bigint'];
它们是属于虚值,可以使用Boolean(value)
或!!value
将其转换为布尔值时,值为false
。
console.log(!!null); // false
console.log(!!undefined); // false
console.log(Boolean(null)); // false
console.log(Boolean(undefined)); // false
接着来看看它们的区别。
undefined
是未指定特定值的变量的默认值,或者没有显式返回值的函数,如:console.log(1)
,还包括对象中不存在的属性,这些 JS 引擎都会为其分配 undefined
值。
let _thisIsUndefined;
const doNothing = () => {};
const someObj = {
a : "ay",
b : "bee",
c : "si"
};
console.log(_thisIsUndefined); // undefined
conso