How to add javascript

Asked

Viewed 2,183 times

0

Inside 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 '*'

  • Are all values numeric? You can try to convert to number like this: var total = (Number(currentUser.profile.hp) + .....)

  • multiplication works

  • if multiplication works, sum must also, unless the values are not numerical, because ai will try to concatenate, try to convert all using Number

1 answer

2


Probably one of them is string and not a 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);

Thus the sign of + will concatenate because the first is a string, of course the multiplication signal works *, for he nay is used for other Javascript operations, such as 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);


A 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 just to add up that takes the arguments and converts/cast:

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);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.