You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JS中使用严格全等!==null出现Uncaught TypeError的原因咨询

问题解析:严格相等!== null vs 非严格相等!= null的差异

先看你代码里的逻辑:遍历嵌套对象链时,最后一个对象Weller没有friend属性,执行currentFrench = currentFrench.friend后,currentFrench的值会变成undefined——这就是问题的核心。

为什么!== null会触发类型错误?

!==是严格相等运算符,会同时比较值和类型:

  • null的类型是null,undefined的类型是undefined,二者类型不同,所以undefined !== null结果为true
  • 循环条件成立,会继续执行console.log(currentFrench.name),但此时currentFrench是undefined,读取它的name属性自然报错

为什么!= null能正常运行?

!=是非严格相等运算符,会先做类型转换再比较:

  • JS里undefined == null的结果是true,所以currentFrench != null会同时排除null和undefined两种情况
  • 当currentFrench变成undefined时,循环条件不成立,直接终止,不会执行报错的那一行

用严格相等实现的正确写法

如果想坚持用严格相等,只需要把条件改成同时判断null和undefined:

const frenchie = {
    name: "Lokys",
    friend: {
        name: "Benken",
        friend: {
            name: "Weller"
        }
    }
}

let currentFrench = frenchie
while(currentFrench !== null && currentFrench !== undefined){
    console.log(currentFrench.name)
    currentFrench = currentFrench.friend
}

或者更简洁的写法(因为这里currentFrench要么是对象,要么是null/undefined,对象属于truthy值,直接判断即可):

while(currentFrench){
    console.log(currentFrench.name)
    currentFrench = currentFrench.friend
}

转换成递归实现

既然你在练习循环转递归,这里是对应的递归版本:

const frenchie = {
    name: "Lokys",
    friend: {
        name: "Benken",
        friend: {
            name: "Weller"
        }
    }
}

function logFriends(obj) {
    // 终止条件:obj为null或undefined时停止
    if (obj == null) return;
    console.log(obj.name);
    logFriends(obj.friend);
}

logFriends(frenchie);

也可以用严格相等的终止条件:

function logFriends(obj) {
    if (obj === null || obj === undefined) return;
    console.log(obj.name);
    logFriends(obj.friend);
}

内容的提问来源于stack exchange,提问作者ashton8504

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 18:30:26