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

ASP.NET Core+React项目中,为何查找数组元素时staticTxt返回undefined?

问题原因与解决方案

你的代码始终返回undefined,大概率是变量类型不匹配导致的。

从你给出的stattxt数据来看,里面的id和taskId都是数字类型(比如1002、5),但如果你的userIdD或者item.id是字符串类型(比如"1002"、"5"),用===全等比较时,会因为类型不同直接返回false,导致filter/find找不到对应项,最终返回undefined。

验证方法

在控制台打印变量类型确认:

console.log(typeof userIdD, typeof item.id);
console.log(typeof stattxt[0].id, typeof stattxt[0].taskId);

如果输出结果里前者是string,后者是number,就坐实了类型不匹配的问题。

解决方法

方法1:统一转为数字类型(推荐)

把userIdD和item.id转成数字后再比较:

// 用Number()转换
const staticTxt = stattxt.find(x => x.id === Number(userIdD) && x.taskId === Number(item.id));

// 或者用parseInt()
const staticTxt = stattxt.find(x => x.id === parseInt(userIdD, 10) && x.taskId === parseInt(item.id, 10));

方法2:使用非全等比较(不推荐,避免隐式转换坑)

如果不想转换类型,可以用==代替===,它会自动做类型转换:

const staticTxt = stattxt.find(x => x.id == userIdD && x.taskId == item.id);

额外排查点

如果类型是匹配的,再确认代码执行时stattxt已经是你打印的完整数组——比如如果stattxt是异步请求回来的数据,可能在这段代码执行时它还处于初始空数组状态,也会导致找不到项。

内容的提问来源于stack exchange,提问作者Mohamed Yousef Khairlden

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 19:07:02