如何解决数组按标识长度分块时indexOf匹配重复数值出错问题
解决方案
你可以直接用指针手动控制遍历位置,不需要依赖indexOf,同时避免遍历和修改原数组同时进行导致的索引混乱:
const splitInput = (input: string[]) => { const chunks: string[][] = []; // 用指针控制当前遍历的位置 let currentIndex = 0; while (currentIndex < input.length) { // 取出当前位置的长度标识 const chunkLen = parseInt(input[currentIndex]); // 截取对应长度的区块 const chunk = input.slice(currentIndex + 1, currentIndex + 1 + chunkLen); chunks.push(chunk); // 指针直接跳过当前长度标识 + 已处理的区块长度,走到下一个长度标识的位置 currentIndex += chunkLen + 1; } return chunks; }
测试效果如下:
const testArr = ["2", "Something1", "Something2", "4", "Something3", "Something4", "Something5", "Something6", "2", "Something7", "Something8"]; console.log(splitInput(testArr)); // 输出:[["Something1", "Something2"], ["Something3","Something4","Something5","Something6"],["Something7", "Something8"]]
如果你的需求确实需要直接修改原数组把处理过的元素移除,也可以调整为splice版本,逻辑一致:
const splitInputAndModifyOrigin = (input: string[]) => { const chunks: string[][] = []; while (input.length > 0) { const chunkLen = parseInt(input[0]); // 移除长度标识 input.shift(); // 取出对应长度的区块,同时从原数组移除 const chunk = input.splice(0, chunkLen); chunks.push(chunk); } return chunks; }
原代码错误原因
- 你在
forEach遍历数组的同时调用splice修改原数组,会导致forEach内部维护的遍历索引和实际数组的位置错位,出现漏遍历或重复遍历的问题 indexOf默认从数组起始位置查找元素,遇到重复的长度数字(比如示例里的两个"2"),就会匹配到已经处理过的第一个"2",导致索引计算完全错误
内容的提问来源于stack exchange,提问作者Filip
相关产品推荐
相关产品推荐

