Summing array on Javascript

前端 未结 5 1956
死守一世寂寞
死守一世寂寞 2021-01-28 03:41

Hi I am trying to sum an array on Javascript with the following codes.

var data[]: 
var total=0;
data.push[x]; // x is numbers which are produced dynamically. 
f         


        
相关标签:
5条回答
  • 2021-01-28 03:45

    Use parseInt() function javascript

    total=parseInt(total)+parseInt(data[i]);
    
    0 讨论(0)
  • 2021-01-28 03:54

    Use parseInt() javascript function....

    total = total + parseInt(data[i]);

    This looks the 'x' which you mention come dynamically has a string type. Just check the "typeof x".

    0 讨论(0)
  • 2021-01-28 03:57

    Try with parseInt:

    total=total+parseInt(data[i]);
    
    0 讨论(0)
  • 2021-01-28 04:03

    Simply whip a unary + before data[i] to convert the string values to numeric values:

    total = total + (+data[i]);
    

    Even better, use += instead of total=total+...:

    total += +data[i];
    

    JSFiddle demo.

    0 讨论(0)
  • 2021-01-28 04:09

    Try this one:

    var total = 0;
    for (var i = 0; i < someArray.length; i++) {
        total += someArray[i] << 0;
    }
    
    0 讨论(0)
提交回复
热议问题