最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

JavaScript function, if else, isNaN - Stack Overflow

programmeradmin2浏览0评论

I've tried to make a function where you're supposed to enter two numbers in two different boxes and loop it until you put in a valid number!

var x = parseInt(prompt("Please enter a number!"));
var y = parseInt(prompt("Please enter a number!"));

function add(x, y) {

    var z = x + y;
    var i = false;

    do {
        if (isNaN(x)) {
            alert("Invalid entry. Please enter a number!")
        } else if (isNaN(y)) {
            alert("Invalid entry. Please enter a number!")
        } else {

            alert(x + " + " + y + " = ");
            i = true;
        }
        while (i == false);
    }
}

add(x, y);

I've tried to make a function where you're supposed to enter two numbers in two different boxes and loop it until you put in a valid number!

var x = parseInt(prompt("Please enter a number!"));
var y = parseInt(prompt("Please enter a number!"));

function add(x, y) {

    var z = x + y;
    var i = false;

    do {
        if (isNaN(x)) {
            alert("Invalid entry. Please enter a number!")
        } else if (isNaN(y)) {
            alert("Invalid entry. Please enter a number!")
        } else {

            alert(x + " + " + y + " = ");
            i = true;
        }
        while (i == false);
    }
}

add(x, y);
Share Improve this question edited Aug 16, 2022 at 12:32 Peter Mortensen 31.6k22 gold badges110 silver badges133 bronze badges asked Apr 6, 2014 at 11:40 user3503415user3503415 51 gold badge1 silver badge3 bronze badges 2
  • 2 How about adding the prompts to the loop so one can actually change the values and not just see the alerts ? – adeneo Commented Apr 6, 2014 at 11:43
  • 1 Wow that is some misleading indentation. And syntactically-invalid code, in fact. – T.J. Crowder Commented Apr 6, 2014 at 11:44
Add a ment  | 

5 Answers 5

Reset to default 1

There are a couple of problems with this code:

  1. Your while is misplaced.
  2. The parameters x and y don't make sense, because the user needs to input them.
  3. The prompts asking for the numbers are outside of the loop.

Here is the fixed code:

function add() {

    do {
        var x = parseInt(prompt("Please enter a number!"));
        var y = parseInt(prompt("Please enter a number!"));
        var z = x + y;
        var i = false;

        if (isNaN(x)) {
            alert("Invalid entry. Please enter a number!")
        } else if (isNaN(y)) {
            alert("Invalid entry. Please enter a number!")
        } else {

            alert(x + " + " + y + " = " + z);
            i = true;
        }
    }
    while (i == false);
}

add();

There are a couple of issues:

  1. It's syntactically invalid. You've ended up with a free-standing while (i == false); (which would fine, but it would never end if i is ever false) and a dangling } under your code. You need to move the while line beneath the closing } of the do.

  2. If x or y is NaN, your add function loops until they change...but no code in that loop ever changes them.

I don't know what you want add to do (since just adding numbers doesn't require a function), but if the goal is to keep prompting the user, you have to move the prompts into the loop:

function add() {

    var x, y, z;
    var valid = false;

    while (!valid) {
        x = parseInt(prompt("Please enter a number!"));
        y = parseInt(prompt("Please enter a number!"));
        valid = !isNaN(x) && !isNaN(y);
        if (!valid) {
            alert("Invalid entry. Please enter a number!")
        }
    }
    z = x + y;
    // Do something with z
}

add();

You can also do it recursively without using a do while loop at all, by asking x and y values until both are correct. Also, note that I used a radix value of 10 for parseInt(string, radix);, the reason being that the documentation describes radix as:

An integer that represents the radix of the above mentioned string. Always specify this parameter to eliminate reader confusion and to guarantee predictable behavior. Different implementations produce different results when a radix is not specified.

See more from the documentation of parseInt.

The code example:

function askXY(x, y) {

  var x_ = x,
      y_ = y;

  if(typeof x_ === "undefined") {
     x_ = parseInt(prompt("Please enter a number for x!"), 10);
  }

  if(typeof y_ === "undefined") {
     y_ = parseInt(prompt("Please enter a number for y!"), 10);
  }

  if(isNaN(x_) || isNaN(y_)) {
     alert("Invalid entry. Please enter a number!");

     // The magic is here, we keep the x or y if either one of those are correct
     // and if not, we give undefined so that value will be asked again from the user
     return askXY(
         !isNaN(x_) ? x_ : undefined,
         !isNaN(y_) ? y_ : undefined
     );
  }

  // success!
  alert(x_ + " + " + y_ + " = " + (x_ + y_));

}

askXY();

See my JSFiddle example.

The isNaN() is a JavaScript function. It returns true if the given value is not a number (NaN).

var a = isNaN('127') ;       // Returns false
var a = isNaN('1273 ') ;     // Returns false
var b = isNaN(-1.23) ;       // Returns false
var c = isNaN(5-2);          // Returns false
var d = isNaN(0) ;           // Returns false
var e = isNaN("Hell  o") ;   // Returns true
var f = isNaN("2005/12/12"); // Returns true

Try this:

$(document).ready(function() {
    var x = parseInt(prompt("Please enter the first number!"));
    var y = parseInt(prompt("Please enter the second number!"));

    function add(x, y) {

        var z = x + y;
        var i = false;

        do {
            if (isNaN(x)) {
                alert("Invalid entry for first number. Please enter a number!");
                x = parseInt(prompt("Please enter first number again!"));
            } else if (isNaN(y)) {
                alert("Invalid entry for second one. Please enter a number!");
                y = parseInt(prompt("Please enter Second number again!"));
            } else {
                   z = x + y;
                alert(x + " + " + y + " = " + z);
                i = true;
            }
        }while (i == false);

    }

    add(x, y);
});

This is a piled demo version. Checkout the Fiddle:

Fiddle

发布评论

评论列表(0)

  1. 暂无评论