简体   繁体   English

打印数组值的总和

[英]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. 您有一个字符串数组,因此Javascript使用+运算符作为串联。 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; 一元+强制Javascript将值视为数字;

There's a Fiddle here 有一个小提琴在这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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