我正在尝试从数组获取existCount,该数组在所选数组中有id。
但是出了点问题,我有一个 id = 5493 的项目,但 existCount.length = 0
我的JS代码:
Chrome 控制台 View :
我的错在哪里?
如何修复它?
谢谢!
最佳答案
问题在于 item.id
和 script.script_id
的类型,您正在比较数字和字符串。
item.id script_id
| |
v v
5493 === "5493" -> false
console.log(5493 === "5493");
另一种方法是将 script_id
转换为数字
此方法使用 +
将该字符串转换为数字并进行正确的比较
console.log(5493 === +"5493");
这是一个说明示例。
var array = [{id: 4110, name: "Ele"}, {id: 4091, name: "SO"}, {id: 5493, name: "Target"}];
var script_id = "5493";
var result = array.filter(e => e.id === +script_id);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
关于javascript - 数组过滤器 linq 未返回预期结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49453683/