gpt4 book ai didi

JavaScript 函数无法正确处理整数

转载 作者:行者123 更新时间:2023-12-01 01:08:05 25 4
gpt4 key购买 nike

我有一个 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(产品)”

最佳答案

首先 - 您应该使用“==”而不是“=”来比较“a”和“b”是否相等。

此外,如果您已经知道“a”大于“b”,则无需检查“==”或“<”,因此最好使用 if-else 结构(甚至 switch)。所以可以优化为:

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');

也使用switch,但 Action 不太明显

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');

关于JavaScript 函数无法正确处理整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55434410/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com