它在输入数字时不会识别“intQuantity”值,只是假设它的ALL true=/
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 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)
只要不是false
、null
、undefined
或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 的功能......但如果规则变得更加复杂,我可以看到它的用途。
相关文章:
- 如何在angularJS中编辑时,如果DB中的值为true,则设置复选框,如果值为false,则取消选中复选框
- AngularJS-使用'true'属性
- JavaScript-切换“;全部检查”;复选框true/false
- location.reload(true)崩溃浏览器选项卡
- 指令的模板必须只有一个根元素:With restrict E&替换true
- JavaScript:只有当数组中的所有项都为true时才执行函数
- 对于loop.if-仅在经过所有间隔后返回true
- if(foo!==null)的计算结果为true,即使foo为null
- ngIf的计算结果始终为true
- 如果函数返回True,则显示Javascript按钮
- (false==false==true)怎么可能是真的
- Javascript If else 只返回 TRUE 或只返回 FALSE
- sails.js beforeCreate方法只接收required设置为true的模型属性
- 在$state.go之后执行$window.location.reload(true)
- 尝试简化检查对象键是否为true并将其推送到另一个对象
- 过滤器返回true或false
- 什么是'true'和'false'和'null'
- 如何使用选项useCSS set true为bxSlider加载onSlideAfter()事件
- 当我的条件为true时,显示一条弹出消息
- 它在输入数字时不会识别“intQuantity”值,只是假设它的ALL true=/