我正试图从一个数组中获取existCount,该数组在所选数组中具有id。
但出了问题,我有一个id = 5493
但existCount.length 0
的项目
我的JS代码:
var existCount = $scope.selectedScript.filter(function (item) {
return item.id === script.script_id;
});
console.log('existCount.length ', existCount.length);
console.log('$scope.selectedScript ', $scope.selectedScript);
console.log('script.script_id ', script.script_id);
Chrome控制台视图:
https://i.stack.imgur.com/4UVWw.png
//对不起,我忘记了第一行输出,但这行在$scope.selectedScript
的顶部,是existCount.length = 0
我的错在哪里?
我该怎么修?
谢谢!
将return item.id === script.script_id;
更改为return item.id == script.script_id;
在您的案例中:item.id是一个数字,script.script_id则是一个字符串。你可以在chrome调试中看到它的颜色,黑色代表字符串,蓝色代表数字。
===在JS中是很难比较的。
您可以在https://stackoverflow.com/a/359509/8572205
因此===returnfalse并且没有项目添加到existCount
如果使用三重等于===
,请确保比较中的两个值的类型相同。我怀疑script.script_id
是一个字符串。
尝试将===
更改为==