我有一个javascript函数,该函数应该询问用户他们要订购多少产品。当他们订购的产品少于一种时,该功能应该发出消息。还应该发送一条警告,说“订购(数量)(产品)[s]”。这些似乎无法正常工作。
我尝试返回数量,但似乎只是将网页更改为数量编号。但是,这确实表明数量有效。
function promptQuantity(product) {
var quantity = prompt("How many " + product + "s would you like?");
if (quantity > 1) {
var plural = "s";
}
if (quantity = 1) {
var plural = "";
}
if (quantity < 1) {
alert("Don't be ridiculous! You can't order less than one " + product + "!");
}
if (quantity > 0) {
alert("Ordering " + quantity + " " + product, plural);
}
}
我希望此功能向用户发送警报,告诉他们他们已经订购了一定数量的产品,但是它只是返回说“订购1(产品)”
答案 0 :(得分:1)
代码段catch
是错误的,您正在执行和分配,if (quantity = 1)
将设置为quantity
,以进行比较,使用1
。但是,您的代码可以像这样重组:
if (quantity == 1)
答案 1 :(得分:1)
首先-您应该使用'=='而不是'='来比较'a'和'b'的相等性。
此外,如果您已经知道'a'大于'b',则无需检查'=='或'<',因此最好使用if-else构造(甚至切换)。因此可以将其优化为:
function promptQuantity(product) {
var quantity = prompt("How many " + product + "s would you like?");
var message = '';
if (quantity > 1) {
message = "Ordering " + quantity + " " + product + "s";
} else if (quantity == 1) {
message = "Ordering " + quantity + " " + product;
} else {
message = "Don't be ridiculous! You can't order less than one " + product + "!"
}
alert(message);
}
promptQuantity('apple');
使用开关,但动作不太明显
function promptQuantity(product) {
var quantity = prompt("How many " + product + "s would you like?");
var message = '';
switch (true) {
case quantity > 1:
message = "Ordering " + quantity + " " + product + "s";
break;
case quantity == 1:
message = "Ordering " + quantity + " " + product;
break;
default:
message = "Don't be ridiculous! You can't order less than one " + product + "!"
break;
}
alert(message);
}
promptQuantity('apple');