如何为每次计算将currentIndex的值设置为0

时间:2018-04-20 17:36:32

标签: javascript

如何将currentIndex的值更改为始终等于0。

来自(CRANK1 + CRANK2)+(DRANK1 + DRANK2)的价格应为(0 +选定金额),但其加价(选择金额+选定金额)

感谢任何帮助,谢谢。  邮件是主要的代码需要文本帖子是主要需要的文本邮件是需要文本的主要代码

var current_division,
    desired_division;


var prices = [
00,09,09,09,09,
12,12,14,14,14,
17,17,17,17,19,
23,24,25,28,28,
35,40,50,65,85,
120,00,00,00,00
];


function getCurrentIndex() {
  return (+document.getElementById("CRANK1").value + 
    +document.getElementById("CRANK2").value);

}

function getDesiredIndex() {
  return (+document.getElementById("DRANK1").value + 
    +document.getElementById("DRANK2").value);
}


function total() {
  var currentIndex = getCurrentIndex();
  var desiredIndex = getDesiredIndex();

   if (desiredIndex < currentIndex) {
    document.getElementById('prices').value = "You can't rank backwards";
    return;
  }

  var accumulatedPrice = 0;
  for(var i = currentIndex; i <= desiredIndex; i++) {
    accumulatedPrice += prices[i];
  }

  document.getElementById('prices').value = accumulatedPrice;
  document.getElementById("prices").readOnly = true;

}

document.getElementById('divboost').addEventListener('change', function() {
  total();
})

HTML

  <form id="divboost" name="priceCalc" action="">
    <br/>
    <select id="CRANK1"> Current Rank
          <option value="0">Bronze</option>
          <option value="5">Silver</option>
          <option value="10">Gold</option>
          <option value="15">Platinum</option>
          <option value="20">Diamond</option>
      </select>
    <br>
    <br/>
    <select id="CRANK2"> Current Divison
          <option value="0">Division 5</option>
          <option value="1">Division 4</option>
          <option value="2">Division 3</option>
          <option value="3">Division 2</option>
          <option value="4">Division 1</option>
      </select>
    <br>
    <br>
    <br/>
    <br/>
    <select id="DRANK1"> Desired Rank
          <option value="0">Bronze</option>
          <option value="5">Silver</option>
          <option value="10">Gold</option>
          <option value="15">Platinum</option>
          <option value="20">Diamond</option>
          <option value="25">Master</option>
      </select>
    <br>
    <br/>
    <select id="DRANK2"> Desired Divison
          <option value="0">Division 5</option>
          <option value="1">Division 4</option>
          <option value="2">Division 3</option>
          <option value="3">Division 2</option>
          <option value="4">Division 1</option>
      </select>
    <br>
    <br>
    € <input type="text" id="prices">
    <br/>
    <br>
  </form>

1 个答案:

答案 0 :(得分:1)

稍微玩了一下后,我注意到你不想将第一个currentIndex添加到accumulatedPrice

通过在循环之前递增currentIndex,您应该获得所需的预期行为

  var accumulatedPrice = 0;
  currentIndex++;
  for(var i = currentIndex; i <= desiredIndex; i++) {
    accumulatedPrice += prices[i];
  }

或者您可以在getCurrentIndex()函数

中为返回值添加1