Reputation: 583
I want to get the sum of my array, I used angular.foreach but when I run the program it keeps displaying "syntax error". What is wrong? The error said is in var sum += value.fare;
I think I made the syntax correct so I am wondering why I get syntax errorThanks
My code is:
angular.forEach($scope.ticketList[fare], function(value, key){
var sum += value.fare;
console.log(sum);
//alert(i);
});
Upvotes: 0
Views: 604
Reputation: 563
first declare the variable sum outside foreach loop
var sum;
angular.forEach($scope.ticketList, function(value, key){
sum=sum+value.fare;
})
Upvotes: 1
Reputation: 4912
You have to define sum
outside your forEach
method, as it doesn't know how to sum during the first iteration (sum is null
at the point of initializing, so you esentially add value.fare
to null
. Try:
var sum = 0;
angular.forEach($scope.ticketList[fare], function(value, key){
sum += value.fare;
});
Upvotes: 1
Reputation: 11620
You need to:
Now your code should work:
var sum = 0;
angular.forEach($scope.ticketList[fare], function(value, key){
sum += value.fare;
});
console.log(sum);
In your code sum was declared i each loop iteration, so it's value was not forwarted to next loop iteration. Extracting it's declaration outside forEach will ensure your values will be preserved, after loop ends.
Upvotes: 1
Reputation: 14037
should not var sum declared outside you cannot define it with assignment :-)
var sum;
angular.forEach($scope.ticketList, function(value, key){
sum += value.fare;
})
;
Upvotes: 1
Reputation: 17064
You are doing +=
which means that the left side should be a value, but you define it each time again using the keyword var
, hence the syntax error.
Define sum
on the outside, then do:
var sum = 0;
angular.forEach($scope.ticketList[fare], function(value, key){
sum += value.fare;
console.log(sum);
//alert(i);
});
Upvotes: 1
Reputation: 4563
Try:
var sum;
angular.forEach($scope.ticketList, function(value, key){
sum += value.fare;
});
If this does not help we need to see your $scope.ticketList
.
Upvotes: 1