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

实现数组元素存在状态切换,是否有更简洁的写法?

优化方案

当然有更简洁高效的实现方式,针对你的场景,这里有几种优化思路:

基础优化版(性能更优)

原代码用filter移除元素会生成新数组,对于大数组来说没必要,直接找到元素索引后用splice删除更高效;同时用indexOf替代find判断存在性,对于简单类型元素性能更好:

const onDateSelected = (date) => {
  const idx = selectedDates.value.indexOf(date);
  if (idx !== -1) {
    selectedDates.value.splice(idx, 1);
  } else {
    selectedDates.value.push(date);
  }
};

极简写法(兼顾简洁性)

如果追求代码更短,可以用三元运算符压缩逻辑,可读性也不差:

const onDateSelected = (date) => {
  const idx = selectedDates.value.indexOf(date);
  idx !== -1 ? selectedDates.value.splice(idx, 1) : selectedDates.value.push(date);
};

复杂元素适配版

如果数组里是对象这类复杂元素,把indexOf换成findIndex,自定义判断条件即可:

const onDateSelected = (date) => {
  // 比如元素是对象,可改为 d.id === date.id 这类匹配逻辑
  const idx = selectedDates.value.findIndex(d => d === date);
  if (idx !== -1) {
    selectedDates.value.splice(idx, 1);
  } else {
    selectedDates.value.push(date);
  }
};

优化点说明

  • 性能提升:indexOf/findIndex找到目标后立即停止遍历,splice直接修改原数组,避免filter遍历整个数组生成新数组的开销。
  • 响应式友好:如果selectedDates是Vue的ref对象,直接操作.value数组而非重新赋值,能保持响应式不被破坏(原代码里的selectedDates = selectedDates.filter(...)会破坏响应式)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 11:07:37