这是我的代码:
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。 谢谢。
答案 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);
}