我的代码的边界总是像2020 4040那样回归,依此类推,我似乎无法弄清楚为什么变量都是数字。我知道这是一个非常简单的修复,但我无法弄清楚。我试过parseInt但是也没用。任何人都可以帮我解释一下我需要添加或改变我的周长来说出40说使用10和10的宽度和高度。
JSON.stringify(this.usermodel)
答案 0 :(得分:0)
prompt
总是返回一个字符串。在执行+
之前,您必须将其转换为数字。否则,它只是连接。
您可以执行类似
的操作var width = parseFloat(prompt("Please enter a width", " "));
答案 1 :(得分:0)
这是因为
var height = prompt("Please enter a height", " ");
获取20的字符串值,而不是20的Number值,我假设你想要。
这可能就是您要找的内容:How do I convert a string into an integer in JavaScript?
答案 2 :(得分:0)
如果你是肯定的,它总会以数字的形式回来。强制它成为一个数字乘以1.乘以https://jsfiddle.net/ktaacx92/
var width = prompt("Please enter a width", " ") * 1;
var height = prompt("Please enter a height", " ") * 1;
但我推荐快速表格。
答案 3 :(得分:0)
将加号(+
)放在prompt()
来电前面。这会将输入转换为数字。 (代码笔:http://codepen.io/anon/pen/jrryBP)。
JS:
function myFunction() {
var width = +prompt("Please enter a width", " ");
var height = +prompt("Please enter a height", " ");
var area = width * height;
var perimeter = (width + height) * 2;
if (width != null && height != null) {
alert("The area is " + area + " and the perimeter is " + perimeter + ".");
}
}
答案 4 :(得分:0)
在提示符周围添加parseInt会将提示字符串解析为int。然后数学将正常工作。 (使用带字符串的+将连接字符串而不是根据需要添加它们。)
array =new int[] { 1, 2, 3, 4, 5};