javascriptchrome-debugging

Javascript filter was unfair


I'm trying to get existCount from an array, which has id in selected array.

But something went wrong, I had an item with id = 5493 but existCount.length 0

My JS code:

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 Console view:

https://i.sstatic.net/4UVWw.png

// Sorry I forgot the first output line, but this line's at the top of $scope.selectedScript and it was existCount.length = 0

Where my fault?

How can I fix it?

Thanks!


Solution

  • Change return item.id === script.script_id; to return item.id == script.script_id;

    In your case: item.id was a number, script.script_id was a string. You can see it in chrome debug by color, black for string, blue for number.

    === is the hard way to compare in JS.

    You can see at https://stackoverflow.com/a/359509/8572205

    So === return false and no item added into existCount