0

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>" );

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Another alternative is to use parseInt(c[i], 10).
1st: Thank you for making my original post look like code. & that worked perfectly!!! I haven't came across that technique yet, but nothing I could find in the book was working. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.