首页 > 解决方案 > 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(产品)”

标签: javascript

解决方案


这段代码if (quantity = 1)是错误的,你正在做和赋值,quantity将被设置为1,以供比较使用if (quantity == 1)。但是,您的代码可以像这样重组:

function promptQuantity(product)
{
    var quantity = prompt("How many " + product + "s would you like?");
    var plural = quantity > 1 ? "s" : "";

    if (quantity < 1)
        alert("Don't be ridiculous! You can't order less than one " + product + "!");
    else
        alert("Ordering " + quantity + " " + product + plural);
}

promptQuantity("Short");


推荐阅读