我正在尝试制作一个程序,为任何数字生成数学表,如下所示:
3 x 1 = 3
3 x 2 = 6
3 x 3 = 9
3 x 4 = 12
我需要用户输入:
(1) 他们需要表格的任何数字(例如 - 3)
(2) 指定一个起点(例如 - 1)
(3) 指定一个终点(例如 - 4)
到目前为止我的有缺陷的代码如下:
function isitanumber(numb){
while (isNaN(numb) == true){
numb = parseInt(prompt("Please add a valid number","5"));
}
}
function mytable (thenum, first, second){
for (var i=first; i<=second; i++){
var y = thenum*i;
document.write(thenum + " x " + i + " = " + y + "</br>");
}
}
var mynum = parseInt(prompt("Enter the number you wish to have the table for", "40"));
mynum = isitanumber(mynum);
var startpoint = parseInt(prompt("Enter the startpoint of the table", "1"));
mynum = isitanumber(startpoint);
var endpoint = parseInt(prompt("Enter the endpoint of the table", "10"));
mynum = isitanumber(endpoint);
mytable(mynum,startpoint,endpoint);
最佳答案
isitanumber
返回您分配给 mynum
的 undefined
(没有 return
语句的函数返回的默认值)每次(mynum = isitanumber(...)
)。因此,mynum
包含undefined
值。
您应该在完成循环 NaN
后返回该变量(并将其分配给适当的变量):
function isitanumber(numb)
{
while (isNaN(numb)) {
numb = parseInt(prompt("Please add a valid number","5"));
}
return numb;
}
function mytable (num, start, end)
{
for (var i = start; i <= end; i++) {
var y = num * i;
document.write(num + " x " + i + " = " + y + "</br>");
}
}
var mynum = parseInt(prompt("Enter the number you wish to have the table for", "40"));
mynum = isitanumber(mynum);
var startpoint = parseInt(prompt("Enter the startpoint of the table", "1"));
startpoint = isitanumber(startpoint);
var endpoint = parseInt(prompt("Enter the endpoint of the table", "10"));
endpoint = isitanumber(endpoint);
mytable(mynum, startpoint, endpoint);
关于javascript - 在 Javascript 中制作数字表程序(如 12 x 1 = 12)时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41446659/