【发布时间】:2018-09-02 08:49:51
【问题描述】:
我正在尝试从 array 中获取 existCount,该数组在所选数组中有 id。
但是出了点问题,我有一个 id = 5493 但 existCount.length = 0
的项目我的 JS 代码:
Chrome 控制台视图:
我的错在哪里?
我该如何解决?
谢谢!
【问题讨论】:
标签: javascript linq.js
我正在尝试从 array 中获取 existCount,该数组在所选数组中有 id。
但是出了点问题,我有一个 id = 5493 但 existCount.length = 0
的项目我的 JS 代码:
Chrome 控制台视图:
我的错在哪里?
我该如何解决?
谢谢!
【问题讨论】:
标签: javascript linq.js
问题在于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; }
【讨论】: