我在编程类的介绍中,其中的赋值是可视逻辑。本周的课程是收集食物摄入量,卡路里摄入量以及我能够用逻辑做的if语句。下一课是网页设计,所以我想为什么不在javascript中尝试相同的东西,并获得一些javascript的经验,但我遇到了问题。我的卡路里用户输入没有转换为整数,我可以将值一起添加。求助,我已阅读,研究并尝试过多种方法。代码如下
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Calorie Burner Program</title>
<script type="text/javascript">
</script>
</head>
<body>
<script type="text/javascript">
//I named my variables here
var TotalCal, Food1, Cal1, Food2, Cal2, Food3, Cal3, Food4, Cal4, Food5, Cal5, Food6, Cal6, Food7, Cal7, Food8, Cal8, Food9, Cal9, Food10, Cal10, Food11, Cal11, Food12, Cal12, Food13, Cal13, Food14, Cal14, Food15, Cal15, Food16, Cal16, Food17, Cal17, Food18, Cal18, Food19, Cal19, Food20, Cal20
//i'm prompting for the food
Food1 = window.prompt("What did you eat today?");
//Here i'm prompting for calories and I would like to reference the input above. as you can see from the code i've tried multiple suggestions
Cal1 = parseInt(prompt("How many calories was " + Food1, "0"), 10);
Food2 = window.prompt("What did you eat today?");
Cal2 = parseInt(prompt("How many calories was " + Food2, "0"), 10);
Food3 = window.prompt("What did you eat today?");
Cal3 = window.prompt("How many calories was" + " " + Food3);
....
Food20 = window.prompt("What did you eat today?");
Cal120 = window.prompt("How many calories was" + " " + Food20)
//you can see below that i've tried multiple methods and i get 5 everytime because my calories is 5 on every item i enter for testing
TotalCal = Cal1, + Cal2, + +Cal3, + +Cal4, + +Cal5, + +Cal6, + +Cal7, + +Cal8, + +Cal9, + +Cal10,+ +Cal11, + +Cal12, + +Cal13, + +Cal14, + +Cal15, + +Cal16, + +Cal17, + +Cal18, + +Cal19
alert("The number of calories you consumed today was " + TotalCal);
</script>
</body>
</html>
答案 0 :(得分:1)
您正在寻找parseInt()
功能。
var numStringOne = "1";
var numStringTwo = "2";
var numOne = parseInt(numStringOne);
var numTwo = parseInt(numStringTwo);
var sum = numOne + numTwo;
> sum == 3 == true
答案 1 :(得分:0)
使用加号转换为数字。
var numStringOne = "1";
var numStringTwo = "2";
var numOne = +numStringOne;
var numTwo = +numStringTwo;
var sum = numOne + numTwo;
if (sum === 3) {
console.log("Hooray!");
}
以下是对此的一些解读:
关于使用parseInt()
的说明,正如另一个人所建议的那样: