0

I'm trying to accumulate a series of numbers in an array e6

Here is the relevant code.

 e3 = prompt(e1 + ", Please enter few numbers (maximum of 6) separated by commas", "1,2,3,4,5");
 e6 = e3.split(',');

for(var a=0;a <= e6.length ;a++) {

       e9=e9 + +e6[a];

    }   
document.write(e9)  ;

However, what get's printed is NaN instead of the default sum of 15. Any ideas how to fix? Thank you.

Edit: Forgot to mention that i already had declared all my variables earlier.

var e1,e2,e3,e4,e5,e6,e7,e8,e9,e10,e11;

Edit2: Here is my entire work in action. https://jsfiddle.net/nhz0Lnx8/

3
  • 2
    Declare your variables with var and initialize e9 to 0. Commented Jun 22, 2016 at 15:58
  • @Pointy No luck. var a = 0; e9 = 0; Commented Jun 22, 2016 at 16:03
  • @andirew1990 From your fiddle (edit #2), it looks like you've solved this problem. Is that correct? Commented Jun 22, 2016 at 16:49

3 Answers 3

1

You should be looking only as far as e6.length-1, but the best solution is to avoid the off by one errors.

var e3 = prompt("Please enter few numbers (maximum of 6) separated by commas", "1,2,3,4,5");
var e6 = e3.split(',');

var e9 = 0;
e3.split(',').map((x)=>{e9 += +x})
document.write(e9) 
Sign up to request clarification or add additional context in comments.

1 Comment

This is for a class, i dont think it would be appropriate to use some of the tools you suggested such as map or the => as we have not discussed them yet. Thanks for your effort though.
1

The error is in the for loop declaration: "a <= e6.length" should be "a < e6.length" ("less than equal or equal" should be changed to "less than")

Comments

0
var e3 = prompt("Please enter few numbers (maximum of 6) separated by commas", "1,2,3,4,5");
var e6 = e3.split(',');

var e9 = 0;

for(var a=0;a < e6.length ;a++) {

       e9 += parseInt( e6[a] );

    }   
document.write(e9)  ;

6 Comments

Didn't change anything. Still display NaN
Please check now. Working fine for me now.
Displays nothing at all now in document.write(e9). i forgot to mention that i already declared all my variables earlier. will edit main post.
@andirew1990 this code does work just fine. Perhaps the surrounding HTML is incorrect.
I managed to get it to work by removing ur trim() part. Now it displays it properly.
|

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.