0

我正在尝试创建一个脚本,该脚本会根据输入的值自动显示价格。

我的价格折扣可能是:

1 item or more = "£5";
5 items or more = "£30";
10 items or more = "£55";

因此,当用户在输入框中输入“7”时,价格显示为£30*7

我知道如何做到这一点的唯一方法是为每种情况制作一个 if else 语句,但我猜有一个更简单的方法?

这是我的伪代码:

<script>

function calc() {
var amountVar = document.getElementById('amount').value;

var discount = new Array();
discount[1] = "£5";
discount[5] = "£30";
discount[10] = "£55";

match = discount where amountVar matches key or more;

document.getElementById('price').innerHTML = match;
}

</script>

<input onkeyup="calc();" id="amount">
<br>
Price: <p id="price"></p>
4

1 回答 1

1

if/else您可以将它们全部放在一个数组中,而不是一个,然后for循环遍历该数组,直到找到匹配的折扣。这有几个优点,主要的一个是在不编写新代码的情况下编辑折扣数组很简单。

// array must be sorted by qty
var discounts = [{qty:1, discount:5}, {qty:5, discount:30}, {qty:10, discount:55}];

function calcPrice (qty) {
    qty = +qty;

    if (qty > 0)
    {
      // look through the array from the end and find first matching discount
      for (var i = discounts.length; i--;) {
          if (qty >= discounts[i].qty) {
              return discounts[i].discount;
          }
      }
    }

    return 0;
}
于 2012-10-26T21:14:16.633 回答