JavaScript 中的基本数据类型包括:String
、Number
、Boolean
、null
、undefined
、BigInt
,其中null
和undefined
都表示“无”这层含义,一般情况下,两者几乎没有区别。
1. 相似之处
在全局定义两个变量,一个是null
,另一个是undefined
,最终他们都被挂载到全局对象上了,且值都为undefined
:
var a = null;
var b = undefined;
console.log(global.a, global.b); // undefined undefined
这说明,null
不是全局对象的一个属性。
另外,在if
语句中,null
和undefined
都会被认为是false
:
var a = null;
var b = undefined;
if (!a) {
console.log(a); // null
}
if (!b) {
console.log(b); // undefined
}
也就是说,在具有类型转换的场景中,null
和undefined
都会被转化为false
:
console.log(!!null); // false
console.log(!!undefined); // false
如下代码,用==
判断null
和undefined
,结果为true
,这是因为它们都被转化为了布尔值的false
。而使用===
判断时,由于它们属于不同的数据类型,则直接会返回false
:
console.log(null == undefined); // true
console.log(null === undefined); // false
2. 不同点
1. null
null
表示一个值被定义了,但定义的是空值。
以下是null
的经典用法。
(1)作为函数的参数,表示不传入此参数。
const test = (a, b) => {
console.log(b);
};
test(null, 2); // 2
(2)作为原型链的终点。
console.log(Object.prototype.__proto__); // null
2. undefined
undefined
表示根本不存在定义。
以下是undefined
的经典用法。
(1)变量被声明,但还没有赋值,此时的变量等于undefined
。
let a;
console.log(a); // undefined
(2)调用函数时,应该传入的参数未传入,则该参数为undefined
。
const test = a => {
console.log(a);
};
test(); // undefined
(3)对象没有定义的属性,该属性为undefined
。
const obj = {};
console.log(obj.a); // undefined
// 注意,在未定义的属性上,继续读取属性会报错
console.log(obj.a.b); // TypeError: Cannot read property 'b' of undefined
(4)不在数组索引范围的值,为undefined
。
const arr = [1];
console.log(arr[100]); // undefined
(5)函数没有返回值时,默认返回的是undefined
。
const test = () => {};
console.log(test()); // undefined
以上是本人学习所得之拙见,若有不妥,欢迎指出交流!
📘📘欢迎在我的博客上访问:
https://lzxjack.top/