【问题标题】:loop instead of if statements for calculation循环而不是 if 语句进行计算
【发布时间】:2017-01-04 22:59:08
【问题描述】:

我正在尝试弄清楚如何将这段代码缩短为一个循环左右。

基本上我有两个需要填写的输入字段:

<input type="number" id="people" name="people" value="0"> 
<input type="text"  id="upprice" name="upprice" value="0">

这是我目前的解决方法:

var upPrice = 0,
    people  = 0;

$('#people').on('change', function() {
    countValue = this.value;

    if (countValue >= 10) {
        upPrice = 1000;
    } 

    if (countValue >= 20) {
        upPrice = 2000;
    } 

    if (countValue >= 30) {
        upPrice = 2500;
    } 

    if (countValue >= 40) {
        upPrice = 3000;
    } 

    $('#upprice').attr('value', upPrice);
});

从技术上讲,这是一种每 10 步触发一次充电的计算。第一个步骤 upcharge 的值为 1000,接下来的两个为 500,依此类推......它会上升到 250。

我想最合理的方法是循环,对吧?不幸的是,我无法正确解决循环,谁能帮助我或给我一个建议如何正确解决这个问题?

【问题讨论】:

  • 你需要一个方程,而不是一个循环。
  • the next two 500 and so on 所以它是 1000,2000,2500,3000 ...下一个增量是多少? “等等”并没有真正帮助下一步,更不用说接下来的 21 步了(我假设 250 是您检查的最大 countValue)
  • 感谢您的快速响应!上面的 sn-p 首先是用于可视化。步骤是:countValue 0-50,upprice = 0 / countValue 50-100,upprice = 1000(每 10 步)/countValue 100-150,upprice = 500(每 10 步),countValue 150-250,upprice = 300(每 10 步)

标签: javascript jquery arrays if-statement input


【解决方案1】:

你可以使用一张桌子 -

var tbl = [0, 1000, 2000, 2500, 3000, and so on];

然后

upPrice = tbl[Math.min(Math.floor(countValue / 10), 25)];

根据 cmets,在 countValue > 50 之后“开始” upPrice

upPrice = tbl[Math.max(Math.min(Math.floor((countValue - 50) / 10), 25), 0)];

【讨论】:

  • 这个计算很好。如果我想在#people 的值达到 50 后每 10 步开始计算怎么办?尝试了一个 if 语句,但它直接执行 5000 而不是从那里从 0 开始。
  • 不知道#people 与这个问题有什么关系......哦,等等,我现在明白了......你试过upPrice = tbl[Math.min(Math.floor((countValue - 50) / 10), 25)];
  • 是的,刚刚试了一下。 upprice 为 NaN,直到达到前 10 个,然后它执行每一步。
  • 哎呀,是的,需要upPrice = tbl[Math.max(Math.min(Math.floor((countValue - 50) / 10), 25), 0)]; 才能将索引正确限制为 0...25
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-03-08
  • 1970-01-01
  • 2021-04-26
  • 1970-01-01
  • 2014-01-27
  • 1970-01-01
  • 2019-04-03
相关资源
最近更新 更多