如何在javascript中添加像1 + 1 + 1 = 3而不是“1”+“1”+“1”= 111的数字

时间:2017-12-19 14:30:13

标签: javascript

这是我的代码:

var health = prompt("Type in health");
var attack = prompt("Type in attack");
var defense = prompt ("Type in defense");
function calculatestats(health,attack,defense){
    return health/4 + attack + defense
}
alert (calculatestats(health,attack,defense));

当我输入4,1和1时,我想输出“3”.javascript正在添加字符“1”,“1”和“1”。我想在数学上添加它,并使其输出3,而不是111。 谢谢。

1 个答案:

答案 0 :(得分:3)

prompt()返回一个字符串。您必须使用+parseInt进行显式类型转换:

function calculatestats(health,attack,defense){
  return +health/4 + +attack + +defense;
}

更好的方式:

function calculatestats(health,attack,defense){
  return parseInt(health)/4 + parseInt(attack) + parseInt(defense);
}
相关问题