JavaScript 函数无法正确处理整数

标签 javascript

我有一个 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/

相关文章:

JavaScript - 使用三元语句中的扩展语法向对象添加属性

javascript - 带有 2 个 if 和 else 条件的 ng-style

javascript - Javascript 日期中的无效日期

javascript - 如何使我的用户响应不区分大小写?

javascript - Dropping Collection后,保存第一条记录时重新创建了Collection,但为什么它的索引没有?

php - 反色情图片上传

javascript - 如何让我的推文按钮将字符串从我的页面拉到新撰写的推文中?

javascript - react : Updating nested component state based on onFocus, "maximum call stack size exceeded"错误

javascript - IE10 控制台在 javascript 错误时不返回行号?

javascript - 术语 'binding' 在 JS 中是什么意思?