为何无法打印被完全覆盖的otherLabels矩形id?代码报错排查
解决嵌套循环变量冲突导致的"Cannot read property 'xMin' of undefined"错误
兄弟,你的报错原因很明确——嵌套循环用了同一个变量i,这直接把遍历逻辑搞乱了!
问题拆解
你写的两层循环都用i当计数器,内层循环跑完时,i已经变成了otherLabels的长度(也就是4)。这时候外层循环继续执行,namedLabels[i]就会访问到数组的越界位置(毕竟namedLabels只有2个元素),自然就会抛出"Cannot read property 'xMin' of undefined"的错误。
另外还有个隐藏问题:你写的覆盖判断条件搞反了!要判断namedLabels的矩形完全覆盖otherLabels的矩形,应该是named的左边界≤other的左边界,named的右边界≥other的右边界,y轴方向同理——不然你现在的条件是在判断other覆盖named,完全和需求相反。
修正后的代码
我把这两个问题都给你改好了,还加了字符串转数字的处理(你的坐标值都是字符串,直接比较会出问题):
// 遍历每个已命名的标签 for (let i = 0; i < namedLabels.length; i++) { // 遍历每个未命名的标签,用独立变量j避免冲突 for (let j = 0; j < otherLabels.length; j++) { const namedRect = namedLabels[i]; const otherRect = otherLabels[j]; // 把字符串坐标转成数字,避免字典序比较错误 const namedXMin = parseInt(namedRect.xMin); const namedXMax = parseInt(namedRect.xMax); const namedYMin = parseInt(namedRect.yMin); const namedYMax = parseInt(namedRect.yMax); const otherXMin = parseInt(otherRect.xMin); const otherXMax = parseInt(otherRect.xMax); const otherYMin = parseInt(otherRect.yMin); const otherYMax = parseInt(otherRect.yMax); // 判断named矩形是否完全覆盖other矩形 const isFullyCovered = namedXMin <= otherXMin && namedXMax >= otherXMax && namedYMin <= otherYMin && namedYMax >= otherYMax; if (isFullyCovered) { console.log(otherRect.id); } } }
关键优化点
- 循环变量分离:内层循环用
j代替i,彻底避免变量覆盖问题 - 类型转换:把字符串类型的坐标转为整数,保证数值比较的正确性
- 修正覆盖逻辑:调整判断条件,符合"named覆盖other"的需求
测试说明
用你提供的测试数据跑的话,目前没有符合覆盖条件的元素(你可以检查下坐标值:比如namedLabels里的两个矩形范围都很小,没法完全包含otherLabels里的任何一个),但代码逻辑已经完全正确了。
内容的提问来源于stack exchange,提问作者user9827152
相关产品推荐
相关产品推荐

