2011-05-09 31 views
0
<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> 
+0

不应该“javscript”是“JavaScript”? – 2011-05-09 21:53:53

+0

感谢您注意到,我很抱歉 – Cool66 2011-05-09 21:54:31

+0

它说intQuantity还未定义=/ – Cool66 2011-05-09 21:55:14

回答

1

您的代码有一些错误。

入住这live example

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(); 
1

两个显而易见的问题(当然,有两件事合作,导致同样的错误):

  • 你永远叫noCharge。而不是if ((intQuantity) == true),你应该说if (noCharge(intQuantity) == true)(或更好,if (noCharge(intQuantity)) ...见下文)。
  • (intQuantity)只要它不是false,null,undefined或0就可以了。就你而言,这是绝大多数时间。

和一对夫妇的风格调:

  • 如果你返回一个布尔值,你真的没有把它比任何东西。而不是说if (noCharge(intQuantity) == true,你可以只说if (noCharge(intQuantity))。要查看是否有错误,请使用!运算符,如if (!noCharge(intQuantity))
  • 您也不必比较两次。布尔值是真或假。 else if...部分可以替换为else,你可以完全摆脱第三部分。
  • 您在noCharge中的规则比他们的要复杂得多。当且仅当数量至少为100时,当前函数才返回true。由于>=涵盖了这一点,因此可以将代码缩减为一行: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 ......但如果规则我可以​​看到使用了它变得更加复杂。

+0

非常感谢你,你不知道我是如何感谢这 – Cool66 2011-05-09 22:08:57

+0

你的权利的方式匈牙利符号是旧的:P – Cool66 2011-05-09 22:19:57

相关问题