Javascript - Separate a string and then add the values

0

I'm starting in javascript and I came across a question. I need the user to enter their date of birth, which I will store day, month and year in different variables. What I need is to separate the values of these variables and then make a sum with them.

For example, the user insists that the birth year is 1994, so I need my program to make 1 + 9 + 9 + 4 = 23, which will be stored in the year variable.

Thank you!

    
asked by anonymous 28.02.2018 / 23:17

2 answers

0

Almost like this:

var str = "1 + 4 + 5";
str = str.repalce(" ",""); //remove os espaços
str = str.split("+"); //transforma a str em array (lista)
for (i=0; i<str.length; i++){ //percorre a lista
    str[i] = parseInt(str[i]); //transforma os valores em inteiros
}

Now you will have a list of integers. Code for list sum:

function soma(lista){
    var total = 0;
    for (i=0; i<lista.length; i++){
        total += lista[i];
    }
    return total;
}

Run like this:

soma(str);
    
28.02.2018 / 23:35
0

Another way is to use reduce :

'1994'.split('').reduce((sum, x) => parseInt(x) + parseInt(sum)) // 23
    
01.03.2018 / 02:03