Asad Mahmood Asad Mahmood - 5 months ago 9
HTML Question

How to make a single string into a multitude of strings?

I have a string called

e3
which holds the string
1,2,4,5,3,6
. I want to add up all of those numbers up to make the number
21
I was considering doing a for loop for this however I do not know how to turn part of a string into its own value.
I anyone has any better idea of what to do please comment, or answer.

Answer

You could use String#split for the string and use Array#reduce for summing.

var e3 = '1,2,4,5,3,6',
    sum = e3.split(',').reduce(function (a, b) { 
      return a + +b; // +b forces b to number
    }, 0);

console.log(sum);