if ... else语句检查NaN和空字符串在JavaScript中不起作用

时间:2016-04-03 16:23:45

标签: javascript function if-statement fizzbuzz

我使用函数重构了FizzBu​​zz,除了函数中的两个if..else语句用于验证用户的输入(validateValue)之外,一切都运行良好。我想提醒用户不允许空字符串,小数和NaN。检查小数的语句有效,但不是空字符串或NaN。当我输入空字符串或NaN时,会出现无小数提示。我想用vanilla JavaScript解决这个问题,没有jQuery。

这是JavaScript:

div

这是HTML:

function getValue(message) {
  var msg = "Please enter a number from 1 to 100.";
  if (message) {
    msg = message;
  }
    return parseInt(prompt(msg)); 
}

function validateValue(num) { 
  if (num === "") { 
    return getValue("Please type something."); 
  } else if (num%1 !== 0) { 
    return getValue("No decimals allowed."); 
  } else if (isNaN(num)) { 
    return getValue("That is not a number!"); 
  } else {
    return num; 
  }
}

function fizzBuzz(num) {
   for (var i = 1; i <= num; i++) {
   if (i%15 === 0) {
    document.getElementById("list").innerHTML += "FizzBuzz<br>";
   }
   else if (i%3 === 0) {
    document.getElementById("list").innerHTML += "Fizz<br>";
  }
  else if (i%5 === 0) {
    document.getElementById("list").innerHTML += "Buzz<br>";
  }
  else {
    document.getElementById("list").innerHTML += i + "<br>";
  }
}
}

  var value = validateValue(getValue());
  fizzBuzz(value); 

3 个答案:

答案 0 :(得分:3)

您可能需要以下内容:

function validateValue(num) {
  if (num === "") {
    return getValue("Please type something."); 
  }

  num = parseFloat(num);

  if (isNaN(num)) {
    return getValue("That is not a number!"); 
  } else if (num%1 !== 0) { 
    return getValue("No decimals allowed."); 
  } else {
    return num; 
  }
}

字符串不能是NaN。因此,在检查它是否为NaN之前,您需要尝试将其转换为数字。

答案 1 :(得分:2)

您可以尝试这样的事情:

&#13;
&#13;
function validate(str) {
  if (validateEmpty(str)) {
    console.log("Input is emply");
  } else if (validateNum(str)) {
    console.log("Value is numeric");
  } else {
    console.log("Invalid Input");
  }
}

function validateEmpty(str) {
  return str === undefined || str == null || str.toString().trim().length === 0;
}

function validateNum(str) {
  var reg = /[0-9]/i;
  return reg.test(str);
}

(function() {
  var a = "";
  validate(a);
  a = "123.46";
  validate(a);
  a = "123.46.57";
  validate(a);
  a = "absl123.46.57";
  validate(a);
  a = "test";
  validate(a);
})()
&#13;
&#13;
&#13;

答案 2 :(得分:1)

谢谢大家!这是我的解决方案,评论说:

function getValue(message) {
  var msg = "Please enter a number from 1 to 100."; // default message
  if (message) {
    msg = message;
  }
    return prompt(msg); // return prompt with appropriate message based on value
}

function validateValue(num) {
  if (num === "") {
    return getValue("Please type something."); // check for empty string
  }

  num = parseFloat(num); // converts string to floating number

  if (isNaN(num)) {
    return getValue("That is not a number!"); // check for NaN
  } else if (num%1 !== 0) { 
    return getValue("No decimals allowed."); // check for decimals
  } else {
    return num; 
  }
}