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

C# 如何在指定RadioButton选中时从Array数组中删除对应元素

实现方案

核心逻辑

  • 首先给每个RadioButton绑定要移除的目标元素值作为自定义属性/value值
  • 监听RadioButton的change选中事件
  • 触发选中事件时,使用数组的filter方法过滤掉目标元素,生成新数组替换原数组即可(不可变操作更安全,避免副作用)

原生JavaScript实现示例

<!-- 单选按钮组 -->
<input type="radio" name="removeItem" value="1" class="remove-radio"> 移除元素1
<input type="radio" name="removeItem" value="3" class="remove-radio"> 移除元素3
<input type="radio" name="removeItem" value="5" class="remove-radio"> 移除元素5
// 原始数值数组
let numArray = [1, 2, 3, 4, 5, 6];
// 绑定所有单选按钮的选中事件
document.querySelectorAll('.remove-radio').forEach(radio => {
  radio.addEventListener('change', function() {
    if(this.checked) {
      // 转为和数组元素一致的数值类型,避免类型不匹配导致移除失败
      const targetItem = Number(this.value);
      // 过滤移除目标元素后赋值给原数组
      numArray = numArray.filter(item => item !== targetItem);
      console.log('移除后数组:', numArray);
    }
  })
})

注意事项

  • 如果数组元素是引用类型(比如对象),调整filter的判断条件匹配唯一标识即可,例如item.id !== targetId
  • 如果需要保留原始数组不被修改,过滤前可以先做一次数组拷贝再操作,例如const newArray = [...numArray].filter(...)
  • Vue/React等框架场景思路完全一致,只需要把事件绑定改为框架内置语法即可,比如Vue的@change、React的onChange,过滤后的数组直接赋值给响应式变量即可生效

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 16:54:04