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

Vue中requestType为数组时如何实现items列表过滤

适配数组类型requestType的过滤方案

不需要手动编写for循环,直接使用JS原生数组API即可兼容两种类型的输入,优化后的代码如下:

return this.items.filter((item) => {
    if (!this.requestType) return true
    const isTypeMatch = Array.isArray(this.requestType)
        ? this.requestType.includes(item.requestsubtypeid)
        : item.requestsubtypeid === this.requestType
    return isTypeMatch && item.status === this.status
})

方案说明

  • 首先用Array.isArray()判断this.requestType的类型,分别处理单值匹配和多值匹配逻辑
  • 数组类型的匹配用原生includes()方法实现,代码简洁度远高于手写for循环,性能和for循环一致均为线性复杂度,没有额外性能损耗
  • 完全保留了原代码的无过滤条件时的放行逻辑,兼容旧版本的数字类型输入场景

可选边界优化

如果存在this.requestType数组内元素类型和item.requestsubtypeid类型不一致的场景(比如数组元素为字符串、id为数字),可以修改匹配逻辑做类型统一:

// 数组元素统一转数字后匹配
? this.requestType.map(Number).includes(item.requestsubtypeid)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.16 10:54:05