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

为何在函数调用中无法访问utils.styles对象的color属性?

问题描述

调用 graphics.drawPoint(ctx,pixelLoc, utils.styles[label].color); 访问 utils.styles 对象的 color 属性时,抛出错误:

Uncaught TypeError: Cannot read properties of undefined (reading 'color')

相关代码片段:

utils.styles={
    car:     { color:'gray',      text:'🚓' },
    fish:    { color:'red',       text:'🐠' },
    house:   { color:'yellow',    text:'🏚' },
    tree:    { color:'green',     text:'🌳' },
    bicycle: { color:'cyan',      text:'🚲' },
    guiter:  { color:'blue',      text:'🎸' },
    pencile: { color:'magenta',   text:'✏'  },
    clock:   { color:'lightgray', text:'⏲' }
}
for(const sample of samples) {
  const {point,label}=sample;
  // 此处调用drawPoint时触发错误
  graphics.drawPoint(ctx,pixelLoc, utils.styles[label].color);
}

注:samples 是包含 label 键的对象集合,声称 label 值与 utils.styles 的键一致(如 ['car','fish','house',...,'clock'])。

排查与解决
  • 检查键名拼写
    注意到 utils.styles 里的 guiter、pencile 可能是拼写错误(正确应为 guitar、pencil)。如果 samples 中的 label 使用的是正确拼写,就会导致 utils.styles[label] 为 undefined。修正 utils.styles 的键名,确保和 label 值完全匹配。

  • 验证label实际值
    在循环中添加日志,打印每个 label 的具体内容,确认是否存在大小写不一致、多余空格或无效值:

    for(const sample of samples) {
      const {point,label}=sample;
      console.log('当前label:', label);
      // 后续代码
    }
    

    比如 'Car'(首字母大写)、'car '(末尾空格)这类值都会导致匹配失败。

  • 添加防御性代码
    即使理论上所有 label 都匹配,也可以通过兜底逻辑避免报错:

    // 方式1:设置默认样式
    const style = utils.styles[label] || { color: 'black' };
    graphics.drawPoint(ctx,pixelLoc, style.color);
    
    // 方式2:先判断存在性再调用
    if(utils.styles[label]) {
      graphics.drawPoint(ctx,pixelLoc, utils.styles[label].color);
    } else {
      console.warn(`未找到label为${label}的样式`);
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 21:58:14