It won't recognize the "intQuantity" value when typing a number , just assumes its ALL true =/
<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 cha开发者_运维问答rge")
}
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>
Your code had some bugs.
Check this 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();
Two obvious problems (well, two things collaborating to cause the same bug):
- You're never calling
noCharge
. Rather thanif ((intQuantity) == true)
, you should be sayingif (noCharge(intQuantity) == true)
(or, better,if (noCharge(intQuantity))
...see below). (intQuantity)
will be truthy as long as it's notfalse
,null
,undefined
, or 0. In your case, that's the vast majority of the time.
And a couple of style notes:
- If you're returning a boolean, you don't really have to compare it to anything. Instead of saying
if (noCharge(intQuantity) == true
, you could just sayif (noCharge(intQuantity))
. To see if something's false, use the!
operator, likeif (!noCharge(intQuantity))
. - You also don't have to compare twice. A boolean is either true or false. The
else if...
part could be replaced with anelse
, and you could be rid of the third section altogether. - Your rules in
noCharge
are more complicated than they have to be. The current function returns true if, and only if, the quantity is at least 100. Since>=
covers that, you could reduce the code to one line:return (intQuantity >= 100)
. - Hungarian notation is dead. Let it rest in peace.
With all that fixed:
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");
}
}
Personally i wouldn't even bother with a function for checking whether something is at least 100...but i can see a use for it if the rules ever get more complicated.
精彩评论