为何在函数调用中无法访问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
相关产品推荐
相关产品推荐

