在 Javascript 中制作数字表程序(如 12 x 1 = 12)时出现问题

Issue with making Number Tables Program (like 12 x 1 = 12) in Javascript

我正在尝试制作一个程序,为任何数字生成数学 tables,如下所示:

3 x 1 = 3

3 x 2 = 6

3 x 3 = 9

3 x 4 = 12

我需要用户输入:

(1) 他们需要 table 的任何数字(例如 - 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 returns undefined(默认值 return 由没有 return 语句的函数编辑),您分配给 mynum每次 (mynum = isitanumber(...))。因此,mynum 包含 undefined 值。

您应该 return 完成循环 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);

您犯了以下错误:

函数return值, 分配起点变量, 分配端点变量

function isitanumber(numb){
    while (isNaN(numb) == true){
            numb = parseInt(prompt("Please add a valid number","5"));
        }
        return numb;
     }


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")); 
startpoint = isitanumber(startpoint);

var endpoint = parseInt(prompt("Enter the endpoint of the table", "10"));  
endpoint = isitanumber(endpoint);


mytable(mynum,startpoint,endpoint);