0

I am trying to add an integer and an array element(also integer) but I seem to be concatenating them instead. How would I add the two together?

i = 0;
var1 = 0;
var2 = prompt("please enter 5 integers separated by commas");
   //1,2,3,4,5  
var2.split(',');
for (i=0;i<5;i++){
    var1 += var2[i];
}

EDIT: Apologies I forgot something that's probably very important. I'll add that now. added the prompt and the split.

3
  • Make var2 = [1,2,3,4,5] and you're good Commented Feb 17, 2016 at 2:59
  • You have edited the question with the correct answer.. Please re run & check. Commented Feb 17, 2016 at 3:02
  • Do you mean you want to add the integer to every element of the array? Commented Feb 17, 2016 at 3:03

3 Answers 3

1

var2.split(',') does not update var2. You would have to do var2 = var2.split(','). You can also use .reduce to sum the array instead of iterating over it with a for loop:

var1 += var2.split(',').map(Number).reduce((prev, next) => prev + next);
Sign up to request clarification or add additional context in comments.

Comments

0

var2 was not an an array, which you have edited. Also instead of 5 put var2.length and declare a variable with var keyword

var i = 0;
var var1 = 0;
var var2 = [1,2,3,4,5,6];  

for (i=0;i<var2.length;i++){
    var1 += var2[i];
}

JSFIDDLE EXAMPLE

NOTE Original question got edited after this post

Comments

0

There are few problems in the script

i = 0;
var1 = 0;
var2 = prompt("please enter 5 integers separated by commas");
//1,2,3,4,5  
var array = var2.split(','); //need to iterate over the array
for (i = 0; i < array.length; i++) { //instead of hardcoded length go by the array length
  console.log(array[i])
  var1 += +array[i]; //or parseInt(var2[i])
}
alert(var1)

Comments

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.