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

TypeScript中如何将字符串数组转换为布尔数组?

解决字符串布尔数组转布尔数组及筛选匹配问题

问题根源

你的筛选结果为空,核心原因是类型不匹配:records里的column是布尔值(true/false),而items是字符串数组("true"/"false")。includes方法使用严格相等(===)判断,布尔值和字符串永远不会匹配,所以筛选不到内容。仅声明items为boolean[]没用,因为TypeScript类型声明只是编译时校验,运行时items实际还是字符串数组。

字符串数组转布尔数组的方法

直接用map遍历数组,通过严格比较转换每个元素:

const strArr = ["false", "true"];
const boolArr = strArr.map(item => item === "true");
// 转换结果:[false, true]

如果需要兼容大小写(比如"TRUE"/"FALSE"),可以先转小写再判断:

const boolArr = strArr.map(item => item.toLowerCase() === "true");

结合筛选的优化写法

你可以选择两种方式实现正确筛选:

  1. 先转换数组再筛选
    把items转成布尔数组后,再用includes匹配:

    const boolItems = this.items.map(item => item === "true");
    const filteredRecords = this.records.filter(x => boolItems.includes(x.column));
    
  2. 直接在筛选中做类型转换
    无需提前转换数组,把布尔值的column转成字符串后再匹配:

    const filteredRecords = this.records.filter(x => {
      const columnStr = x.column.toString();
      return this.items.includes(columnStr);
    });
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 02:31:03