0

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);
      });
1
  • Fist of all your sum should be outside of forEach. Commented Feb 17, 2015 at 8:43

6 Answers 6

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

1

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);
});

Comments

1

should not var sum declared outside you cannot define it with assignment :-)

var sum;
angular.forEach($scope.ticketList, function(value, key){  
    sum += value.fare;
})

;

Comments

1

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;
});

Comments

1

first declare the variable sum outside foreach loop

var sum;
angular.forEach($scope.ticketList, function(value, key){  
    sum=sum+value.fare;
})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.