Javascript Data Type How to - Sum array element








Question

We would like to know how to sum array element.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
var data = ["5","11","16","7"];
var total=0;
for(var i=0, n=data.length; i < n; i++) { 
  total += +data[i];<!--from   w w w  .  ja v  a  2  s  .  c  o  m-->
}
document.writeln(total)

</script>
</head>
<body>
</body>
</html>

The code above is rendered as follows: