Google Apps Script循环迭代遗漏问题排查与修复
问题分析与修复方案
问题原因
使用for...in遍历数组时,调用splice删除元素会导致数组长度缩短、后续元素前移,但for...in会按原数组的索引顺序遍历,跳过了前移后占据被删除索引位置的元素,最终出现漏删情况。
以你的代码为例:
原数组索引与元素对应关系:
- 0: "Test 1-Coms-2A Up"
- 1: "Test 1-Included Units-10G"
- 2: "test 2-Included Units-1000 Sa"
- 3: "test 2-Percentage-MB"
当循环到索引1并删除该元素后,数组变为:
- 0: "Test 1-Coms-2A Up"
- 1: "test 2-Included Units-1000 Sa"
- 2: "test 2-Percentage-MB"
但for...in的下一个遍历索引直接跳到2,跳过了现在索引1的元素,导致它未被检查和删除。
修复方案
方案1:倒序遍历数组
从数组末尾往前遍历,删除元素不会影响未遍历的索引,避免跳过问题:
function test(){ var Concat_names = ["Test 1-Coms-2A Up", "Test 1-Included Units-10G", "test 2-Included Units-1000 Sa", "test 2-Percentage-MB"]; for (var i = Concat_names.length - 1; i >= 0; i--) { console.log(Concat_names[i]); var check_included_units = Concat_names[i].includes("Included Units"); console.log(check_included_units) if (check_included_units) { Concat_names.splice(i,1); } } console.log(Concat_names); }
方案2:使用filter方法(推荐)
filter方法返回新数组,自动过滤不符合条件的元素,代码简洁且不修改原数组的遍历逻辑:
function test(){ var Concat_names = ["Test 1-Coms-2A Up", "Test 1-Included Units-10G", "test 2-Included Units-1000 Sa", "test 2-Percentage-MB"]; Concat_names = Concat_names.filter(item => !item.includes("Included Units")); console.log(Concat_names); }
方案3:正向遍历并调整索引
若坚持正向遍历,删除元素后将索引减1,确保下次循环检查当前位置的新元素:
function test(){ var Concat_names = ["Test 1-Coms-2A Up", "Test 1-Included Units-10G", "test 2-Included Units-1000 Sa", "test 2-Percentage-MB"]; for (var i = 0; i < Concat_names.length; i++) { console.log(Concat_names[i]); var check_included_units = Concat_names[i].includes("Included Units"); console.log(check_included_units) if (check_included_units) { Concat_names.splice(i,1); i--; // 删除后索引回退,避免跳过元素 } } console.log(Concat_names); }
内容的提问来源于stack exchange,提问作者Shaik Naveed
相关产品推荐
相关产品推荐

