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

JS新手实现LeetCode expect函数遇报错:Cannot read properties of undefined

问题排查与代码修正

核心错误点

  • expect函数未返回目标对象:你定义的expect函数里写了toBe和notToBe两个内部函数,但最后没有把这两个方法包装成对象返回。调用expect(5)时得到的是undefined,自然无法读取toBe属性,这就是Cannot read properties of undefined (reading 'toBe')报错的根源。
  • 用了非严格相等判断:题目明确要求用===(严格相等)和!==(严格不等),你用的==会自动做类型转换(比如0 == "0"会返回true),不符合题目要求的判断逻辑。
  • 错误处理方式不符合要求:题目要求不满足条件时抛出错误,不是返回错误字符串。必须用throw new Error("错误信息")来抛出异常,而非return字符串。

修正后的代码

var expect = function(val) {
    // 返回包含两个方法的对象
    return {
        toBe(val2) {
            if (val === val2) {
                return true;
            } else {
                throw new Error("Not Equal");
            }
        },
        notToBe(val2) {
            if (val !== val2) {
                return true;
            } else {
                throw new Error("Equal");
            }
        }
    };
};

// 测试示例(需用try-catch捕获抛出的错误)
try {
    expect(5).toBe(7); // 会抛出"Not Equal"错误
} catch (err) {
    console.log(err.message);
}

try {
    expect(5).notToBe(5); // 会抛出"Equal"错误
} catch (err) {
    console.log(err.message);
}

关于LeetCode解决方案里的冒号用法

你看到的冒号是对象字面量的方法定义语法,比如:

return {
    toBe: function(val2) { ... }
}

这是在对象中给toBe属性赋值一个函数,ES6之后可以简写为toBe(val2) { ... },两种写法功能完全一致,都是在返回的对象上挂载可调用的方法。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 15:36:22