在JavaScript中,null
和 undefined
是两个表示“无”或“空”的值,但它们具有不同的含义和应用场景。
undefined
。undefined
。undefined
。undefined
。null
是一个表示“无”的对象,转为数值时为 0
。null
是一个表示空指针的对象,表示该处不应该有值。null
必须显式地赋值给变量。undefined
是一个类型,它只有一个值,即 undefined
。null
是一个对象类型,它只有一个值,即 null
。undefined
。null
表示该变量有意地持有空值。undefined == null
返回 true
,因为它们在非严格相等比较时被认为是相等的。undefined === null
返回 false
,因为它们的类型不同。let a; // a 的值为 undefined
console.log(a); // 输出: undefined
let b = null; // b 的值为 null
console.log(b); // 输出: null
console.log(undefined == null); // 输出: true
console.log(undefined === null); // 输出: false
function test() {
// 没有返回值,默认返回 undefined
}
console.log(test()); // 输出: undefined
let obj = {};
console.log(obj.nonExistentProperty); // 输出: undefined
obj.emptyProperty = null;
console.log(obj.emptyProperty); // 输出: null
问题:为什么我的变量有时是 undefined
,有时是 null
?
原因:
undefined
。null
时,它是 null
。解决方法:
===
) 来区分 undefined
和 null
。通过这种方式,你可以更精确地控制和管理你的代码中的空值状态。
领取专属 10元无门槛券
手把手带您无忧上云