起因
一个数组['中', '发', '白'],执行了以下删除元素的代码后,一直删不干净,并且只剩下一个['发']。重点代码在下方for循环中。
watch: {availableParList: {handler (newValue) {this.chainSettings = { ...this.item, checkList: newValue }if (this.chainSettings.checkList) {// 如果在选完第二步后,回到第一步中所选的参与方被删除,第二步则应同步删除刚才所选的参与方for (let i = 0; i < this.chainSettings.participantNames.length; i++) {let item = this.chainSettings.participantNames[i]if (!_.find(newValue, { name: item })) {this.chainSettings.participantNames.splice(i, 1)}}}},immediate: true},
原因
是因为在边循环边删除,this.chainSettings.participantNames 这个数组,长度是在变短的,删完第一个元素,就只剩下['中','白'],再进入循环时,this.chainSettings.participantNames[1]其实也就是删掉了['白']这个元素,下次循环时,此时i已经等于2了,数组长度是1,就不会再进入循环了。
解决办法
- 可以倒序循环,但注意 i 的取值
for (let i = this.chainSettings.participantNames.length; i > 0; i--) {let lastItem = this.chainSettings.participantNames[i-1] // 这里很容易错,注意是i-1if (!_.find(newValue, { name: lastItem })) {console.log('doit')this.chainSettings.participantNames.splice(i-1, 1)}}}
总结
这应该是最初级的错误了吧,看来以后还是要刷一刷LeetCode,锻炼一下逻辑能力,希望不要再犯此类错误。
