在javaScript中,将一个变量赋值为null和undefined,老实说几乎没区别
let a = null
let b = undefined
console.log(a == b); // true
相同点:
在 if 语句中 null 和 undefined 都会转为false两者用相等运算符比较也是相等
let a = null
let b = undefined
console.log(Boolean(a)); // false
console.log(Boolean(b)); // false
区别:
1. undefined表示定义了并未赋值
null表示定义了,值null
2. 隐式转换不同
let a = null
let b = undefined
console.log(Number(a)); // 0
console.log(Number(b)); // NaN
3. 应用场景不同
# null
1) null表示没有对象,可能将来要赋值一个对象,即该处不应该有值
2) 作为对象原型链的终点 Object.prototype.__proto__ = null
3) 在代码后面给变量赋值,可以释放变量所占的内存
# undefined
1) 对象属性名不存在时,输出undefined
2) 函数没有写返回值,即没有写return,拿到的是undefined
3) 定义了形参,没有传实参,显示undefined
4) 写了return,但没有赋值,拿到的是undefined
代码如下:
let obj = {
name:'zbt'
}
console.log(obj.age); // undefined
function fn() {}
console.log(fn()); // undefined
function fn(x) {
console.log(x); // undefined
}
fn()
function fn() {
return
}
console.log(fn()); // undefined