1

Having trouble adding a value to an element array. An example of what I currently have.

array[1] current example is value of 10
var total = array[1] + 1; // result is 101

I need total to be 11, I also tried the bellow example, same thing.

var total = array[1].toString() + 1; // result 101
nnnnnn
  • 147,572
  • 30
  • 200
  • 241
Alex _TNT
  • 309
  • 1
  • 2
  • 12
  • 3
    `var total = +array[1] + 1;` – Pranav C Balan Jul 14 '16 at 08:55
  • 1
    Using `.toString()` is the opposite of what you need, because your array appears to contain strings already - is there a reason you didn't populate it with numbers rather than strings? – nnnnnn Jul 14 '16 at 08:55

2 Answers2

1

Convert the string to Number before the addition otherwise, string concatenation will happen.

var total = +array[1] + 1;

Refer : How do I convert a string into an integer in JavaScript?

Community
  • 1
  • 1
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
1

10 must be in string format, Use parseInt or Uniary_plus to convert it to number

var array = ['10'];
var total = parseInt(array[0],10) + 1;
alert(total)

JSFIDDLE

brk
  • 48,835
  • 10
  • 56
  • 78