最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

how to add array element values with javascript? - Stack Overflow

programmeradmin5浏览0评论

I am NOT talking about concatenating elements together, but adding their values to another separate variable.

Like this:

var TOTAL = 0;
for (i=0; i<myArray.length; i++) {
    TOTAL += myArray[i];
}

With this code, TOTAL doesn't add mathematically element values together, but it concatenates them next to each other, so if myArray[0] = "10" and myArray[1] = "10" then TOTAL will be "01010" instead of 20.

How should I write what I want?

Thanks

I am NOT talking about concatenating elements together, but adding their values to another separate variable.

Like this:

var TOTAL = 0;
for (i=0; i<myArray.length; i++) {
    TOTAL += myArray[i];
}

With this code, TOTAL doesn't add mathematically element values together, but it concatenates them next to each other, so if myArray[0] = "10" and myArray[1] = "10" then TOTAL will be "01010" instead of 20.

How should I write what I want?

Thanks

Share Improve this question edited Mar 26, 2024 at 15:04 jo3rn 1,4211 gold badge15 silver badges30 bronze badges asked Nov 25, 2009 at 18:55 user188962user188962
Add a ment  | 

5 Answers 5

Reset to default 7

Sounds like your array elements are Strings, try to convert them to Number when adding:

var total = 0;
for (var i=0; i<10; i++){
  total += +myArray[i];
}

Note that I use the unary plus operator (+myArray[i]), this is one mon way to make sure you are adding up numbers, not concatenating strings.

const myArray = [2, 4, 3];
const total = myArray.reduce(function(a,b){ return +a + +b; });

A quick way is to use the unary plus operator to make them numeric:

var TOTAL = 0;
for (var i = 0; i < 10; i++)
{
    TOTAL += +myArray[i];
}

Make sure your array contains numbers and not string values. You can convert strings to numbers using parseInt(number, base)

var total = 0;
for(i=0; i<myArray.length; i++){
  var number = parseInt(myArray[i], 10);
  total += number;
}

Use parseInt or parseFloat (for floating point)

var total = 0;
for (i=0; i<10; i++)
 total+=parseInt(myArray[i]);
发布评论

评论列表(0)

  1. 暂无评论