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

TypeScript中如何在if语句内访问并过滤数组数据

解决数组过滤无法访问数据的问题

你的代码里存在几个关键问题,导致过滤逻辑没生效:

  • 分支判断逻辑错误:selection初始值是空字符串,this.selection != null的判断永远为true(空字符串不等于null),所以else分支永远不会执行。
  • 过滤条件写死,未关联选择值:当前过滤条件固定匹配black和#000,没有用到用户选择的selection变量,完全不符合动态过滤的需求。
  • 过滤函数未触发:你只在点击事件里给selection赋值,但没有调用filterArray,导致过滤逻辑根本没执行,自然看不到console输出。

修正后的代码

data = [
    { color: "red", value: "#f00" },
    { color: "green", value: "#0f0" },
    { color: "blue", value: "#00f" },
    { color: "cyan", value: "#0ff" },
    { color: "magenta", value: "#f0f" },
    { color: "black", value: "#000" }
];

selection: string = "";

onClick($event: any) {
    this.selection = $event.value;
    // 点击后立即执行过滤逻辑
    this.filterArray();
}

filterArray(): void {
    let myData = this.data;
    // 空字符串、null、undefined会被自动判定为false
    if (this.selection) {
        // 根据selection动态过滤,可按需调整匹配规则(color/value)
        let filteredData = myData.filter(x => x.color === this.selection || x.value === this.selection);
        console.log(filteredData);
    } else {
        console.log(myData);
    }
}

额外说明

  • 按需调整过滤规则:如果selection只匹配color字段,就把条件改成x.color === this.selection;只匹配value就用x.value === this.selection。
  • 用===做严格相等判断,避免隐式类型转换导致的意外问题。
  • 确保filterArray在合适的时机被调用,比如点击事件、数据更新后等。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 04:40:55