为什么在输入字段中输入数字并将其与Math结合时,我会获得NaN?

时间:2017-09-13 17:05:30

标签: javascript html math

我想计算所有边的体积和长度,但是当我在提示中输入数字时,我得到了NaN。为什么不起作用?

var length = document.getElementById("length");
var answer = document.getElementById("answer");
var sides = document.getElementById("sides");


var side = prompt("Enter the length/height/width of your cube", 2);



length.innerText = side;


var volume = Math.pow(side,3);
var sidesmax = length*12;
answer.innerText = volume;
answer.innerText = sidesmax;
<p>
One side of your cube has a measurement of <span id="length">___</span> units.
</p>
<p>
Your cube has a volume of <span id="answer">___</span> units cubed.
</p>
<p>
Your cube has max side length of <span id="answer">___</span>.
</p>

3 个答案:

答案 0 :(得分:1)

所以你有一些错误。

这一行:

var sidesmax = length*12;

应该是这样的:

var sidesmax = side * 12;

这些行都使用相同的元素,称为answer

answer.innerText = volume;
answer.innerText = sidesmax;

对两个跨度使用不同的id并为它们分别使用变量。

对于小整数幂,通常使用*而不是Math.pow,但两者都可以使用:

var volume = side * side * side;

另请注意,变量side包含字符串,而不是数字。对于涉及*Math.pow的操作,这无关紧要,因为自动类型强制将为您转换,但如果您尝试使用其他运算符(例如+),则会对其进行处理作为一个字符串。

var length = document.getElementById("length");
var sidesAnswer = document.getElementById("sidesAnswer");
var volumeAnswer = document.getElementById("volumeAnswer");
var sides = document.getElementById("sides");

var side = prompt("Enter the length/height/width of your cube", 2);

length.innerText = side;

var volume = side * side * side;
var sidesmax = side * 12;
volumeAnswer.innerText = volume;
sidesAnswer.innerText = sidesmax;
<p>
One side of your cube has a measurement of <span id="length">___</span> units.
</p>
<p>
Your cube has a volume of <span id="volumeAnswer">___</span> units cubed.
</p>
<p>
Your cube has max side length of <span id="sidesAnswer">___</span>.
</p>

答案 1 :(得分:0)

问题在于此行var sidesmax = parseInt(length)*12;您将12与字符串(__)相乘。通过删除文件,代码运行良好。

var length = document.getElementById("length");
var answer = document.getElementById("answer");
var sides = document.getElementById("sides");


var side = prompt("Enter the length/height/width of your cube", 2);



length.innerText = side;

console.log(side);
var volume = Math.pow(side,3);

// var sidesmax = parseInt(length)*12; // multiplying string with 1
answer.innerText = volume;
answer.innerText = sidesmax;

答案 2 :(得分:0)

var length = document.getElementById("length");
var answer = document.getElementById("answer");
var sides = document.getElementById("sides");


var side = prompt("Enter the length/height/width of your cube", 2);



length.innerText = side;


var volume = Math.pow(side,3);
var sidesmax = length*12;
answer.innerText = volume;
answer.innerText = sidesmax;
<p>
One side of your cube has a measurement of <span id="length">___</span> units.
</p>
<p>
Your cube has a volume of <span id="answer">___</span> units cubed.
</p>
<p>
Your cube has max side length of <span id="answer">___</span>.
</p>