简体   繁体   中英

Print Sum of Array Values

I am trying to find and print the total of the array, but it only prints the array. Any suggestions on where I went wrong?

var c = new Array(
    "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13",
    "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", 
    "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", 
    "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", 
    "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "60", "61", 
    "62", "63", "64", "65", "66", "67", "68", "69", "70", "71", "72", "73", 
    "74", "75", "76", "77", "78", "79", "80", "81", "82", "83", "84", "85", 
    "86", "87", "88", "89", "90", "91", "92", "93", "94", "95", "96", "97", 
    "98", "99", "100"
) 

var total = 0;

for ( var i = 0; i < 100; ++i )
{

    total += c [ i ];
}

document.writeln( "<p>The total of array c is: " + total + "</p>" );

You have an array of strings, so Javascript uses the + operator as a concatenation. You need to change the values to numbers first.

Try this:

for ( var i = 0; i < 100; ++i ) {
  total += (+c[i]);
}

The unary + forces Javascript to treat the value as a number;

There's a Fiddle here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM