// 判断一个变量是否为 null 的示例代码
let myVar = null;
// 方法 1: 使用严格相等运算符 (===)
if (myVar === null) {
console.log("myVar 是 null");
} else {
console.log("myVar 不是 null");
}
// 方法 2: 使用 typeof 检查
// 注意:typeof null 返回 "object",因此这种方法不能单独用来判断 null
if (typeof myVar == "object" && myVar === null) {
console.log("myVar 是 null");
} else {
console.log("myVar 不是 null");
}
严格相等运算符 (===):这是最常用的方法来判断一个变量是否为 null。它不会进行类型转换,只有当变量的值和类型都与 null 相同时才会返回 true。
typeof 操作符:虽然 typeof null 返回 "object",但它可以与其他条件结合使用来确保更严格的检查。不过,通常情况下直接使用 === 就足够了。
如果你需要进一步的判断或处理其他类型的值(如 undefined),可以根据具体需求扩展这些方法。
上一篇:js 判断是否为对象
下一篇:js 判断null
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站