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

JavaScript中如何检测未定义变量?现有代码报错求助

正确检测未定义变量的方案

你的代码存在两个关键问题,导致了ReferenceError:

  1. typeof判断错误:typeof 返回的是字符串类型,你应该和字符串 'undefined' 对比,而非直接和 undefined 这个值比较。
  2. 变量作用域问题:else 块内用 let 声明的 profileChart 是块级作用域变量,出了这个块就无法被访问,下次执行判断时变量依然处于未定义状态。

修正后的代码

// 先在外部作用域声明变量,保证后续判断和使用能访问到
let profileChart;

if (typeof profileChart !== 'undefined' && profileChart) {
    profileChart.destroy();
} else {
    profileChart = new Chart(
        pisteElevationProfileChart,
        configPiste
    );
}

额外说明

  • 加入 && profileChart 是为了避免变量已声明但未赋值(比如初始为null)的情况,确保调用destroy()时变量是有效的Chart实例。
  • 确保profileChart的作用域能覆盖所有需要判断和使用它的代码区域,避免因作用域隔离导致的访问问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 05:05:54