Lee Lee
Lee Lee

Reputation: 583

angular.forEach syntax error

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

Answers (6)

siddhesh
siddhesh

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

Fengson
Fengson

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

Beri
Beri

Reputation: 11620

You need to:

  • move sum outside of forEach loop
  • init sum with default vlaue, 0 for int, "" for string.

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

squiroid
squiroid

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

Omri Aharon
Omri Aharon

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

DonJuwe
DonJuwe

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

Related Questions