它在输入数字时不会识别“intQuantity”值,只是假设它的ALL true=/

It won't recognize the "intQuantity" value when typing a number , just assumes its ALL true =/

本文关键字:假设 true ALL 数字 输入 识别 intQuantity      更新时间:2023-09-26
<script ="javscript"/>
function checkQuantity()
{
function noCharge(intQuantity){
  if (intQuantity > 100) {
    return true;
  }
  if (intQuantity < 100) {
    return false;
  }
  return true;
}
checkQuantity=parseInt(prompt("Please enter the quantity of light bulbs",""))
if ((intQuantity)==true)
{
    alert("Your light bulbs will arrive shortly. There is NO delivery charge")
}
else if ((intQuantity)==false)
{
    alert("Your light bulbs will arrive shortly. There will be a  delivery charge of £5.99")
}
else
{
    alert("Please enter an amount")
}
}
</script>

你的代码有一些错误。

查看此实时示例

function checkQuantity() {
    function noCharge(intQuantity) {
        if (intQuantity > 100) {
            return true;
        }
        if (intQuantity < 100) {
            return false;
        }
        return true;
    }
    var amount = noCharge(parseInt(prompt("Please enter the quantity of light bulbs", "")));
    if (amount == true) {
        alert("Your light bulbs will arrive shortly. There is NO delivery charge")
    }
    else if (amount == false) {
        alert("Your light bulbs will arrive shortly. There will be a  delivery charge of £5.99")
    }
    else {
        alert("Please enter an amount")
    }
}
checkQuantity();

两个明显的问题(嗯,两件事协同导致相同的错误):

  • 你从来不打电话给noCharge. 与其说if ((intQuantity) == true),不如说if (noCharge(intQuantity) == true)(或者,更好的是,if (noCharge(intQuantity))......见下文)。
  • (intQuantity)只要不是falsenullundefined或0,就是真实的。 在您的情况下,这是绝大多数时间。

还有一些风格说明:

  • 如果您要返回布尔值,则实际上不必将其与任何东西进行比较。 与其说if (noCharge(intQuantity) == true,不如说if (noCharge(intQuantity))。 要查看某些内容是否为假,请使用 ! 运算符,例如 if (!noCharge(intQuantity))
  • 您也不必比较两次。 布尔值要么为真,要么为假。 else if...部分可以用else代替,你可以完全去掉第三部分。
  • 您在noCharge中的规则比它们必须的要复杂得多。 当前函数返回 true,当且仅当数量至少为 100。 由于>=涵盖了这一点,因此您可以将代码减少到一行:return (intQuantity >= 100)
  • 匈牙利符号已死。 让它安息吧。

修复了所有这些问题:

 function checkQuantity() {
    function noCharge(quantity) {
        return (quantity >= 100);
    }
    var quantity = parseInt(prompt("Quantity:", ""));
    if (noCharge(quantity)) {
        alert("No delivery charge");
    } else {
        alert("Delivery charge of $5.99");
    }
}

就我个人而言,我什至不会费心检查某物是否至少为 100 的功能......但如果规则变得更加复杂,我可以看到它的用途。