I have a function in Angular that's looping through an array:
$scope.things = [{ num: 4 }, { num: 2 }];
$scope.specialThings = [];
$scope.doThings = function() {
for (var i = 0; i < things.length; i++) {
// do some things
}
$scope.specialThings = $scope.things.filter(function(x) {
return x.num > 2;
});
console.log($scope.specialThings);
};
The for loop is changing, say, the num
attribute of items in my things
array.
I then use that filter function to isolate a special subset of things
. When none of the items match the condition in my filter, console.log
prints Array[0]
. However, when some items DO match, I get the following:
[Object]
length: 0
__proto__: Array[0]
I have no idea what's going on. Help!
It's hard to tell what is the problem without a running example in a jsfiddle but I suspect it's the missing $scope before things.length in your for loop that cause a silent error. So your filter never execute.
Try this:
$scope.doThings = function() {
for (var i = 0; i < $scope.things.length; i++) {
// do some things
}
$scope.specialThings = $scope.things.filter(function(x) {
return x.num > 2;
});
console.log($scope.specialThings);
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.