从数组索引提取坐标:最后一个顶点处理异常问题排查
问题排查与修复
核心问题1:indexOf参数类型不匹配
处理最后一个点h时,代码使用vertexLetters.indexOf(foundPoints)查找索引,但foundPoints是数组(如["h"]),而vertexLetters是字符串类型。用数组在字符串中查找会直接返回-1,导致后续previousLetter变为undefined,引发异常。
修复:将查找参数改为单个字符foundPoints[0]:
let lastLetterIndex = vertexLetters.indexOf(foundPoints[0]);
核心问题2:插入坐标时产生嵌套数组
vertexList[previousLetter].slice(-1)返回的是包含坐标的数组(如[[3,6]]),直接用splice插入会让vertexList["h"]变成嵌套数组([[[3,6]], [4,6]]),不符合预期的二维数组格式。
修复:取出slice(-1)返回数组中的实际坐标元素:
// 方式1:直接提取坐标元素 vertexList[foundPoints[0]].splice(0, 0, vertexList[previousLetter].slice(-1)[0]); // 方式2:用展开运算符展开数组 vertexList[foundPoints[0]].splice(0, 0, ...vertexList[previousLetter].slice(-1));
修复后的关键代码片段
if (g == icon.length - 1) { console.log('last Point?: ' + foundPoints); let lastVertix = vertexList[foundPoints[0]]; console.log('lastVertix: ' + lastVertix); // 修正查找参数为单个字符 let lastLetterIndex = vertexLetters.indexOf(foundPoints[0]); let previousLetter = vertexLetters[lastLetterIndex - 1]; console.log('previousLetter: ' + previousLetter); console.log('last point: ' + vertexList[previousLetter].slice(-1)); // 插入实际坐标而非嵌套数组 vertexList[foundPoints[0]].splice(0, 0, vertexList[previousLetter].slice(-1)[0]); }
验证结果
修复后,vertexList["h"]会被正确设置为[[3,6], [4,6]],其中[3,6]是g的终点坐标,[4,6]是h自身的坐标,符合线条从g到h的连接需求。
内容的提问来源于stack exchange,提问作者train_lviv_19
相关产品推荐
相关产品推荐

