You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让步骤数组的splice方法仅执行一次,避免回退后点击按钮重复删除步骤

问题原因

你当前的写法是直接在原始步骤数组上调用splice方法修改原数组,每次回退页面后再点击按钮,操作的已经是之前被删减过的数组,自然会出现重复删除元素的问题。

解决方法

推荐优先用「动态生成新数组」的方案,从根源避免原数组被反复修改的问题:

步骤1:先在服务中保留原始完整的步骤数组

不要直接修改原始数组,每次都基于原始数组生成符合条件的步骤列表:

// step.service.ts 中定义
export class StepService {
  // 保留原始完整步骤,永远不修改
  originalSteps = [
    FirstStep,
    SecondStep,
    ThirdStep,
    FourthStep,
    SuccessPageComponent
  ];
  // 实际使用的动态步骤
  steps = [...this.originalSteps];
}

步骤2:nextStep方法基于原始数组生成新数组,不用splice修改原数组

nextStep() {
  const value = { ...this.form.value };
  // 每次都从原始数组拷贝生成新数组,避免操作已被修改的旧数组
  let filteredSteps = [...this.stepService.originalSteps];
  if (value.type === 'once') {
    // 按组件过滤而非按索引删,后续调整步骤顺序也不会出问题
    filteredSteps = filteredSteps.filter(step => step !== ThirdStep);
  }
  if (value.type === 'multiple') {
    filteredSteps = filteredSteps.filter(step => step !== SecondStep);
  }
  // 赋值给实际使用的步骤数组
  this.stepService.steps = filteredSteps;
}

可选补充:如果一定要用splice

如果必须使用splice操作,需要先做前置判断,避免重复删除:

nextStep() {
  const value = { ...this.form.value };
  // 每次操作前先重置为原始数组
  this.stepService.steps = [...this.stepService.originalSteps];
  if (value.type === 'once' && this.stepService.steps[2] === ThirdStep) {
    this.stepService.steps.splice(2, 1);
  }
  if (value.type === 'multiple' && this.stepService.steps[1] === SecondStep) {
    this.stepService.steps.splice(1, 1);
  }
}

内容的提问来源于stack exchange,提问作者user17205093

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 15:06:07