Summing array on Javascript

前端 未结 5 2033
死守一世寂寞
死守一世寂寞 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 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.

提交回复
热议问题