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");
结合筛选的优化写法
你可以选择两种方式实现正确筛选:
先转换数组再筛选
把items转成布尔数组后,再用includes匹配:const boolItems = this.items.map(item => item === "true"); const filteredRecords = this.records.filter(x => boolItems.includes(x.column));直接在筛选中做类型转换
无需提前转换数组,把布尔值的column转成字符串后再匹配:const filteredRecords = this.records.filter(x => { const columnStr = x.column.toString(); return this.items.includes(columnStr); });
内容的提问来源于stack exchange,提问作者deanpillow
相关产品推荐
相关产品推荐

