javascript当中null和undefined的==和===的比较

博客主要探讨了null和undefined在使用==和===进行比较时的差异。==只需值相同即可,而===要求类型也必须相等。还展示了声明变量后默认值为undefined,以及通过代码示例对null和undefined的相关判断进行了演示。

例 3.1.3(null和undefined的==和===的比较)

<head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
</head>
<script>
    //马克-to-win:声明变量x
    /* if a value is not set, its typeof is undefined, its value is undefined, if a value= null, its typeof is object, its value
is null,but when you use == to test, they are the same, but when to
use === to test, they are not the same,== means as long as value is the same, ok, but === means type also must be equal. */
    var x;
    var z1 = "d";
    var y = null;

    //      document.writeln("z1 is"+z1);
    /*if you cancel commenting out the following statement, it will give the blank page, which means it has error.*/
    //        document.writeln(zyx);
    document.writeln(x + " is x");
    document.writeln(typeof(x) + " is typeof(x)");
    document.writeln(y + " is y");
    document.writeln(typeof(y) + " is typeof(y)");
    var z = undefined;
    document.writeln(z + " is z");
    document.writeln(typeof(z) + " is typeof(z)");
    if (y == undefined)
    {
        document.writeln('null and undefined is interchangable');
    }
    if (z1 != null)
    {
        document.writeln('z1 != null');
    }
    if (y === undefined)
    {
        document.writeln('null and undefined is exactly the same');
    }
    if (x == undefined)
    {
        document.writeln('声明变量后默认值为undefined');
    }

    if (x === undefined)
    {
        document.writeln('声明变量后默认值为exactly the same as undefined');
    }

    if (x == null)
    {
        document.writeln('声明变量后默认值为null');
    }

更多请见:https://blog.youkuaiyun.com/qq_44594249/article/details/99689140

<think> 我们正在讨论的是 JavaScript 中的 `!== undefined` `!== null` 的作用。根据之前的引用,我们知道 `undefined` `null` 都是原始数据类型,在条件判断中都被视为 `false`,但它们有一些重要的区别。 引用[1]指出:null 表示变量无值但占用内存空间,undefined 表示变量声明了但未赋值。另外,typeof null 为 'object',而 typeof undefined 为 'undefined'。 引用[3]详细说明了:未初始化的变量会被自动赋值为 undefined,而 null 必须由代码显式赋值。此外,它们在算术运算中的行为也不同:undefined 参与运算会得到 NaN,而 null 会被转换为0。 现在,我们关注的是 `!== undefined` `!== null` 在编程中的作用: 1. `!== undefined`:用于检查变量是否已经定义并且被赋值(不是未定义状态)。它可以避免引用未声明变量导致的错误(但注意,对于未声明的变量直接使用会报错,所以通常用typeof检查)。 2. `!== null`:用于检查变量是否不是空值(即显式赋值为null的情况)。 在实际编程中,我们经常需要区分一个变量是未定义(undefined)还是定义但为空(null),或者两者都不是(有实际值)。使用严格不等于操作符可以帮助我们精确地排除这两种特殊情况。 示例1:检查变量是否已定义且非undefined 有时我们想确认一个变量已经声明且被赋值(不是默认的undefined),可以使用: ```javascript if (variable !== undefined) { // 这里variable不是undefined,可能是null或其他值 } ``` 示例2:检查变量是否非null 如果我们想排除变量为null的情况: ```javascript if (variable !== null) { // 这里variable不是null,可能是undefined或其他值 } ``` 但是,注意:如果我们同时想排除undefinednull,通常使用: ```javascript if (variable != null) { // 注意:这里使用的是松散不等于(!=),它会同时排除nullundefined // 因为null == undefined 为true,所以variable != null 等价于 variable !== null && variable !== undefined } ``` 这是因为在JavaScript中,`null == undefined` 返回true(引用[2]提到:nullundefined==比较中不会发生类型转换,但它们是相等的)。所以,当我们写`variable != null`时,实际上也排除了undefined。 然而,如果我们想要分别处理,或者只排除其中一种,那么就需要单独使用`!== undefined`或`!== null`。 另外,为了避免未声明变量直接使用导致的引用错误,我们通常使用typeof来检查undefined: ```javascript if (typeof variable !== 'undefined') { // 这样即使variable未声明也不会报错,而是返回'undefined'字符串 } ``` 而对于null,由于typeof null返回'object',所以我们可以这样检查: ```javascript if (variable !== null) { // 注意:这里variable必须已声明,否则会报错 } ``` 或者结合使用: ```javascript if (typeof variable !== 'undefined' && variable !== null) { // 安全的检查:既不是未定义,也不是null } ``` 总结: - `!== undefined` 用于排除值为 `undefined` 的情况(但注意直接使用可能因变量未声明而报错,因此常用 `typeof variable !== 'undefined'`)。 - `!== null` 用于排除值为 `null` 的情况(要求变量已声明,否则报错)。 在实际应用中,根据需求选择使用。常见场景包括: 1. 函数参数默认值:ES6之前,我们常用 `if (param !== undefined)` 来检测参数是否传入(因为未传入的参数为undefined)。 2. 从对象中获取属性时,如果属性不存在,返回undefined,我们可以用 `obj.prop !== undefined` 判断属性是否存在。 3. 当需要明确区分一个变量是未被初始化(undefined)还是被显式清空(null)时,分别使用这两个操作符。 注意:在ES6中,我们可以使用默认参数空值合并运算符(??)来简化这些操作,但理解背后的原理仍然重要。 根据上述内容,我们生成回答。 </think> ### `!== undefined` `!== null` 在编程中的作用详解 在 JavaScript 中,`!== undefined` `!== null` 用于精确排除特定类型的空值,它们在变量检查、函数参数验证数据处理中有重要作用: #### 1. **`!== undefined` 的核心作用** - **检测未定义状态**:验证变量是否已被声明或初始化 - **典型场景**: - 检查函数参数是否传递 - 验证对象属性是否存在 - 避免未初始化变量导致的引用错误 ```javascript function calculate(a, b) { if (b !== undefined) { // 检测第二个参数是否传递 return a + b; } return a * 2; // 未传递时的默认逻辑 } calculate(5); // 返回 10 (执行默认逻辑) calculate(5, 3); // 返回 8 ``` - **安全替代方案**:优先使用 `typeof x !== 'undefined'`,可避免未声明变量报错[^3] #### 2. **`!== null` 的核心作用** - **排除显式空值**:确认变量不是被主动赋值的空指针 - **典型场景**: - 检测 API 返回的有效数据 - 验证 DOM 元素是否存在 - 过滤数据库查询结果中的空值 ```javascript const userResponse = fetchUserData(); // 可能返回 null if (userResponse !== null) { renderProfile(userResponse); // 仅在有数据时渲染 } else { showError("用户数据不存在"); } ``` #### 3. **关键区别与注意事项** | 特性 | `undefined` | `null` | |---------------------|--------------------------------------|----------------------------| | **产生原因** | 变量未初始化/属性不存在[^1] | 显式赋值的空值[^3] | | **typeof 检测** | `'undefined'` | `'object'`(历史遗留)[^1] | | **数值转换** | `NaN` | `0`[^1] | | **相等性规则** | `null == undefined` 为 `true`[^2] | `null === undefined` 为 `false`[^4] | ```javascript // 区别演示 let x; console.log(x !== undefined); // false(x未定义) console.log(x !== null); // true(x不是主动赋值的null) const y = null; console.log(y !== undefined); // true(y已定义) console.log(y !== null); // false(y就是null) ``` #### 4. **实用技巧与最佳实践** - **组合使用**:同时排除 `null` `undefined` ```javascript if (value != null) { // 等效 value !== null && value !== undefined // 利用了 null == undefined 的规则[^2] } ``` - **默认值模式**:配合空值合并操作符 `??` ```javascript const username = input ?? "匿名用户"; // 仅在 null/undefined 时用默认值 ``` - **类型安全验证**:在 TypeScript 中显式标注 ```typescript function save(data: string | null) { if (data !== null) { // 此处 data 自动推断为 string 类型 } } ``` > **关键原则**: > - 使用 `!== undefined` 确认**存在性** > - 使用 `!== null` 确认**有效性** > - 两者结合可确保处理真实有效的数据,避免常见的空指针错误[^3][^4]
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

mark_to_win

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值