简体   繁体   English

此代码中的全局和局部范围有问题吗?

[英]Issue with global and local scope in this code?

I am testing this code to ensure that user only adds a number and when he does, I want to alert that number. 我正在测试此代码,以确保用户仅添加一个号码,当他添加时,我想提醒该号码。 If i test with only letters on first prompt and then change to a number on the second prompt, it still gives me a NaN. 如果我在第一个提示符下仅测试字母,然后在第二个提示符下更改为数字,它仍然会给我一个NaN。 how to rectify this: 如何纠正这个问题:

var mynum = prompt("Enter the number you wish");

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

isitanumber(mynum);
alert("The number you have added is " + mynum);

Your code should work fine. 您的代码应该可以正常工作。 You forgot to grab the value from your second prompt though. 但是,您忘记了从第二个提示中获取值。 This could work: 这可以工作:

var mynum = prompt("Enter the number you wish");

function isitanumber(numb){
    while (isNaN(numb) == true){
        numb = prompt("Please add a valid number");
    }
    //This sets the value you are displaying to the new input
    mynum = numb;
 }

isitanumber(mynum);

alert("The number you have added is " + mynum);

Here is this code running: https://jsfiddle.net/ruvn2uf0/ 这是正在运行的代码: https : //jsfiddle.net/ruvn2uf0/

My best guess would be that your mynum variable doesn't get the updated value once user enters any text at initial prompt . 最好的猜测是,一旦用户在初始prompt输入任何文本,您的mynum变量就不会获得更新的值。 So I would suggest you to return the value everytime back from the calling function and update your global variable. 因此,我建议您每次从调用函数return该值并更新全局变量。

 var mynum = prompt("Enter the number you wish"); function isitanumber(numb) { while (isNaN(numb)) { return parseInt(prompt("Please add a valid number")); //return } } mynum = isitanumber(mynum); //update the variable alert("The number you have added is " + mynum); 

You could also use do-while in this case as below: 在这种情况下,您也可以使用do-while ,如下所示:

 var mynum; do{ mynum = parseInt(window.prompt("Please enter a number", "")); }while(isNaN(mynum)); alert("The number you have added is " + mynum); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM