JavaScript中数组的求和值

时间:2016-04-25 08:40:26

标签: javascript html arrays

我正在尝试在javascript变量中执行添加方法,下面是我的代码:

<html>
<body>
  <p id="demo"></p>
  <p id="demo1"></p>
  <p id="demo2"></p>
  <script>
  var juice = [];
  var water = [];
  var fruits = [2, 5, 7, 10,15, 25,28,34,38,45,49,52,55,57,59];
  for(var i =0;i < fruits.length;i++){
        var today = new Date();
        var numberOfDaysToAdd = fruits[i] ;
        today.setDate(today.getDate() + numberOfDaysToAdd); 
        var dd = today.getDate();
        var mm = today.getMonth()+1; //January is 0!
        var yyyy = today.getFullYear();
        if(dd<10) {
           dd='0'+dd
        } 
        if(mm<10) {
           mm='0'+mm
        } 
        today = mm+'/'+dd+'/'+yyyy+' $ ';

     juice[i] = today;
    for( var j=0; j<=juice.length; j++)
   {
        water[j] += juice[j][4];

   }

  }
  document.getElementById("demo").innerHTML = juice.length;
  document.getElementById("demo1").innerHTML = juice;
  document.getElementById("demo2").innerHTML = water;
  </script>    
</body>
</body>
</html>

我想对上面的水变量添加 4 并打印输出,我尝试编码如上,但我无法实现功能。

2 个答案:

答案 0 :(得分:2)

Try using Array.prototype.reduce as below

var a = [1,3,5,6,9,12,16, 18];
var sum = a.reduce(function (prev, current) {
            return prev + current
          }, 0);

document.querySelector('#content').innerHTML = sum;
<div id='content'> </div>

If you need to add 4 to each use Array.prototype.map as below:

    var a = [1,3,5,6,9,12,16, 18];
    var sum = a.map(function (val) {
                return val + 4;
              });

    document.querySelector('#content').innerHTML = sum;
<div id='content'></div>

答案 1 :(得分:0)

The statement water[j] += juice[j][4]; in the second for loop won't work because you're using the += operator with array elements that have never been defined to begin with. For example if I have:

var x = [];
x[0] += 1;

this results in NaN. If I do it with strings like so:

var x = [];
x[0] += 'a';

it results in 'undefineda'. So that needs to be changed.

Secondly, what kind of integer addition you are trying to do? juice is an array of strings such as '04-24-2016' based on your code. Do you mean to add 4 days to whatever date is stored in juice[j]?