2011-05-09 34 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

相關問題