How to do sum in javascript

0

Within a function I entered this code and for some reason it is not adding up.

var total = (currentUser.profile.hp + currentUser.profile.attack + currentUser.profile.luck) / 3; 

multiplication works perfectly with the '*' character

    
asked by anonymous 16.05.2018 / 18:47

1 answer

2

Probably some of them are string and not Number , see the difference:

//Com string
var currentUser = {
    profile: { hp: "300", attack: 100, luck: 10 }
};

console.log(currentUser.profile.hp + currentUser.profile.attack + currentUser.profile.luck);

//Com Number/sem string:
currentUser = {
    profile: { hp: 300, attack: 100, luck: 10 }
};

console.log(currentUser.profile.hp + currentUser.profile.attack + currentUser.profile.luck);

In this way the + sign will concatenate because the first one is string , of course the multiplication sign works * , since it not is used for other JavaScript operations , how to concatenate, it is only used for mathematical operations see:

var currentUser = {
    profile: { hp: "300", attack: 100, luck: 10 }
};

var total = currentUser.profile.hp * currentUser.profile.attack * currentUser.profile.luck; 

console.log(total);

One possible solution is to put a 1 * in front:

var total = (1 * "10") + (1 * "11");

console.log(total);

Or use Number

var total = Number("10") + Number("11");

console.log(total);

Facilitating

To facilitate all this you can create a function only to add which takes the arguments and converts / cast them:

function Somar(){
    var soma = 0;

    for (var i = arguments.length - 1; i >= 0; i--) {
        soma += Number(arguments[i]);
    }

    return soma;
}

var currentUser = {
    profile: { hp: "300", attack: 100, luck: 10 }
};

var total = Somar(currentUser.profile.hp, currentUser.profile.attack, currentUser.profile.luck) / 3;

console.log(total);
    
16.05.2018 / 19:04