大值循环中的JavaScript问题

时间:2018-11-27 16:46:00

标签: javascript

我的循环有问题。

如果我使用余额:20000,apr:20%,最低每月还款额(利息):余额的1 + 1%。

我以不同的方式尝试,没有成功。请给我建议。

我的代码如下:

function getInterest() {
  var interest = document.getElementById('interest').value;
  return interest;
}

function getPayments(minimumPayment, originalBalance, interestRate) {


  var balance = document.getElementById("balance").value;
  const payments = [];
  /*console.log(`======originalBalance======`, originalBalance);
  console.log(`======minimumPayment======`, minimumPayment);
  console.log(`======interestRate======`, interestRate);*/
  //debugger;
  //for (let month = 0; month < 60; month++)
  while (1) {
    let balance = originalBalance / 1;
    let payment = minimumPayment * balance / 100;
    if (payment < 10) payment = 10;
    const interest = ((interestRate / 12) * balance / 100);
    const principal = payment - interest;

    //alert(principal;
    balance -= principal;

    payments.push({
      payment: +payment.toFixed(2),
      principal: +principal.toFixed(2),
      balance: +balance.toFixed(2)
    })
    originalBalance = balance;

    if (interest <= 0) break;
  }
  console.log(payments.length);



  //console.log(`===========`, payments);
  var option1 = Math.round(payments.length / 12);
  var option2 = Math.round(payments.length / 12);
  var option3 = Math.round(payments.length / 12);
  if (option1) {
    document.getElementById('option1').innerHTML = option1;
    var years1 = ' Years';
    document.getElementById('years1').innerHTML = years1;
  }

  if (option2) {
    document.getElementById('option2').innerHTML = option2;
    var years2 = ' Years';
    document.getElementById('years2').innerHTML = years2;
  }
  if (option3) {
    document.getElementById('option3').innerHTML = option3;
    var years3 = ' Years';
    document.getElementById('years3').innerHTML = years3;
  }

  return payments;
}



function Calculate() {

  /*var formatter = new Intl.NumberFormat('en-US', {
      style: 'currency',
      currency: 'USD',
      minimumFractionDigits: 2,
  });*/


  //grab value from function
  var interestResult = getInterest();

  var balance = document.getElementById("balance").value;
  var aprRate = document.getElementById("aprRate").value;

  var onePercent = balance / 100;
  var annualInterest = (balance * aprRate / 100) / 12;


  //minimum payment drop down
  switch (interestResult) {
    case "0":
      interestResult = (parseFloat(Math.round(onePercent + annualInterest).toFixed(2)));
      document.getElementById('rate').innerHTML = interestResult;
      document.getElementById('rate2').innerHTML = interestResult;
      break;
    case "2.00":
      interestResult = (parseFloat(Math.round(balance * 2 / 100).toFixed(2)));
      document.getElementById('rate').innerHTML = interestResult;
      document.getElementById('rate2').innerHTML = interestResult;
      break;
    case "2.08":
      interestResult = (parseFloat(Math.round(balance * 2.08 / 100).toFixed(2)));
      document.getElementById('rate').innerHTML = interestResult;
      document.getElementById('rate2').innerHTML = interestResult;
      break;
    case "2.50":
      interestResult = (parseFloat(Math.round(balance * 2.50 / 100).toFixed(2)));
      document.getElementById('rate').innerHTML = interestResult;
      document.getElementById('rate2').innerHTML = interestResult;
      break;
    case "2.78":
      interestResult = (parseFloat(Math.round(balance * 2.78 / 100).toFixed(2)));
      document.getElementById('rate').innerHTML = interestResult;
      document.getElementById('rate2').innerHTML = interestResult;
      break;
    case "3.00":
      interestResult = (parseFloat(Math.round(balance * 3 / 100).toFixed(2)));
      document.getElementById('rate').innerHTML = interestResult;
      document.getElementById('rate2').innerHTML = interestResult;
      break;
    case "3.50":
      interestResult = (parseFloat(Math.round(balance * 3.50 / 100).toFixed(2)));
      document.getElementById('rate').innerHTML = interestResult;
      document.getElementById('rate2').innerHTML = interestResult;
      break;
    case "4.00":
      interestResult = (parseFloat(Math.round(balance * 4 / 100).toFixed(2)));
      document.getElementById('rate').innerHTML = interestResult;
      document.getElementById('rate2').innerHTML = interestResult;
      break;
    case "4.50":
      interestResult = (parseFloat(Math.round(balance * 4.50 / 100).toFixed(2)));
      document.getElementById('rate').innerHTML = interestResult;
      document.getElementById('rate2').innerHTML = interestResult;
      break;
    case "5.00":
      interestResult = (parseFloat(Math.round(balance * 5.00 / 100).toFixed(2)));
      document.getElementById('rate').innerHTML = interestResult;
      document.getElementById('rate2').innerHTML = interestResult;
      break;
  }

  var additionalMonthlyPayment = document.getElementById('additionalMonthlyPayment').value;
  var interestResult2 = interestResult;

  var interestResult3 = interestResult;
  document.getElementById("rate3").value = interestResult3;

  //input file fixedMonthlyPaymentTxt
  document.getElementById("fixedMonthlyPaymentTxt").innerHTML = interestResult3;

  //variable to pass to <span id="balanceTxt"></span>
  var balanceTxt = balance;
  document.getElementById('balanceTxt').innerHTML = balanceTxt;

  //variable to pass to <span id="aprTxt"></span>
  var aprTxt = aprRate;
  document.getElementById('aprTxt').innerHTML = aprTxt;

  //input field = firstMinimumPaymentTxt
  var firstMinimumPaymentTxt = interestResult3;
  document.getElementById('firstMinimumPaymentTxt').innerHTML = firstMinimumPaymentTxt;

  //input field = additionalMonthlyPaymentTxt
  var additionalMonthlyPayment2 = additionalMonthlyPayment;

  if (additionalMonthlyPayment2 == 0) {
    document.getElementById('additionalMonthlyPaymentTxt').innerHTML = "$0";
  } else {
    document.getElementById('additionalMonthlyPaymentTxt').innerHTML = additionalMonthlyPayment2;
  }

  var interestRate = aprRate;
  //Interest Rate = 17.5
  //alert(interestRate);

  var minimumPayment = getInterest();
  const payments = getPayments(minimumPayment, balance, interestRate);



  var originalBalanceOption1 = balance;
  var originalBalanceOption2 = balance;
  var originalBalanceOption3 = balance;

  document.getElementById('originalBalanceOption1').innerHTML = originalBalanceOption1;
  document.getElementById('originalBalanceOption2').innerHTML = originalBalanceOption2;
  document.getElementById('originalBalanceOption3').innerHTML = originalBalanceOption3;

  //totalMonthlyPayment

  var totalMonthlyPayment = parseInt(interestResult3) + parseInt(additionalMonthlyPayment2);
  if (isNaN(totalMonthlyPayment)) {
    return 0;
  } else {
    document.getElementById('totalMonthlyPayment').innerHTML = totalMonthlyPayment;
  }




}
.button {
  border-radius: 10px;
  background-color: #003366;
  border: none;
  color: #FFFFFF;
  text-align: center;
  font-size: 28px;
  padding: 20px;
  width: 200px;
  transition: all 0.5s;
  cursor: pointer;
  margin: 5px;
}

.button span {
  cursor: pointer;
  display: inline-block;
  position: relative;
  transition: 0.5s;
}

.button span:after {
  content: '\00bb';
  position: absolute;
  opacity: 0;
  top: 0;
  right: -20px;
  transition: 0.5s;
}

.button:hover span {
  padding-right: 25px;
}

.button:hover span:after {
  opacity: 1;
  right: 0;
}

.button-green {
  border-radius: 10px;
  background-color: #4CAF50;
  border: none;
  color: #FFFFFF;
  text-align: center;
  font-size: 28px;
  padding: 20px;
  width: 200px;
  transition: all 0.5s;
  cursor: pointer;
  margin: 5px;
}

.button-green span {
  cursor: pointer;
  display: inline-block;
  position: relative;
  transition: 0.5s;
}

.button-green span:after {
  content: '\00bb';
  position: absolute;
  opacity: 0;
  top: 0;
  right: -20px;
  transition: 0.5s;
}

.button-green:hover span {
  padding-right: 25px;
}

.button-green:hover span:after {
  opacity: 1;
  right: 0;
}

input[type="text"] {
  color: #000;
  border: 1px solid #ccc;
  border-radius: 3px;
  padding: 3px;
  height: 50px !important;
  max-width: 300px;
  font-size: 22px !important;
  font-weight: bold;
}

select {
  max-width: 300px;
  height: 50px !important;
  font-weight: bolder;
  color: #000;
}

.form-control {
  display: block;
  width: 100%;
  height: 34px;
  padding: 6px 12px;
  font-size: 16px !important;
  font-weight: bolder !important;
  line-height: 1.42857143;
  color: #000;
  background-color: #fff;
  background-image: none;
  border: 1px solid #ccc;
  border-radius: 4px;
  -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
  box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
  -webkit-transition: border-color ease-in-out .15s, -webkit-box-shadow ease-in-out .15s;
  -o-transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;
  transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;
}

.numberResult {
  font-size: 18px;
  font-weight: bold;
  color: #000;
}

.input-group-extended {
  position: relative;
  border-collapse: separate;
}

h1.headers {
  color: #267cac;
  font-weight: bold;
  font-size: 24px;
}

.readonly {
  color: forestgreen;
  ;
  font-size: 40px;
  font-weight: bolder;
  border-color: #fff;
}


/**
    table
 */

.table {
  font-size: 12px;
}

th {
  background-color: #f0f0f0;
  color: green;
  font-weight: bolder;
  font-size: 12px;
  text-transform: uppercase;
}

tr {
  background-color: #f8f8f8;
}

td {
  color: #000;
  font-weight: bold;
}
<div style="padding: 100px 20px 100px 20px; ">

  <div class="container">

    <div class="row" style="background-color: #ededed; border-bottom: 10px #cdcdcd solid; padding: 20px;">
      <link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
      <div class="col-md-12">
        <h3 style="font-family: 'Roboto Condensed', sans-serif; color: green;">
          Debt Calculator
        </h3>
      </div>
      <div class="col-md-12" style="height: auto; padding: 20px;">

        <div class="col-md-12" style="border:1px solid #cfcfd4; background-color:#f0f0f2; padding:20px;">
          <div class="col-md-12">
            <div class="form-row">
              <label for="balanceLabel"><h1 class="headers">Balance Actual:</h1></label>
              <div class="input-group">
                <span class="input-group-addon">$</span>
                <input type="number" min="0" step="0.01" data-number-to-fixed="2" data-number-stepfactor="100" class="form-control currency" id="balance" required />
              </div>
            </div>
          </div>
          <div class="col-md-12">
            <div class="form-row">
              <label for="aprLabel"><h1 class="headers">*APR:</h1></label>
              <div class="input-group-extended">
                <input type="number" min="0" step="0.01" data-number-to-fixed="2" data-number-stepfactor="100" class="form-control currency" id="aprRate" />
              </div>
            </div>
          </div>
          <div class="col-md-12">
            <button class="button-green" type="submit" onclick="return Calculate();">
                            <span>CALCULATE</span>
                        </button>
          </div>
          <div class="col-md-12">
            <h1 class="headers">Opción de pago #1: Pago Mínimo Solamente</h1>
            <p>Esta opción calcula cuánto tiempo tardará en pagar el saldo de su tarjeta de crédito si planea realizar los pagos mensuales mínimos solamente</p>
          </div>
          <div class="col-md-12">
            <h1 class="headers">Minimum monthly payment calculation:</h1>
            <div class="form-group">
              <label for="interest"> Cálculo del pago mínimo mensual:
                            </label>
              <select class="form-control" id="interest" onchange="getInterest(); Calculate();  ">
                <option>Select Rate</option>
                <option value="1.00">Interest + 1% Balance</option>
                <option value="2.00">2%</option>
                <option value="2.08">2.08%</option>
                <option value="2.50">2.5%</option>
                <option value="2.78">2.78%</option>
                <option value="3.00">3.0%</option>
                <option value="3.50">3.5%</option>
                <option value="4.00">4%</option>
                <option value="4.50">4.5%</option>
                <option value="5.00">5%</option>
              </select>
            </div>
            <p>Basado en la información provista, su primer pago mensual es</p>
            <div style="padding: 20px;">
              <span id="rate" class="readonly" style="align-content: center;"></span>.
            </div>
            <p>
              Tenga en cuenta que el pago mínimo disminuye a medida que usted pague el balance de su tarjeta de crédito
            </p>
          </div>
          <div class="col-md-12">
            <h1 class="headers">Payment Option #2: Minimum Payment Plus</h1>
            <p>This option estimates how long it takes to pay off your credit card if you commit to paying a set amount in addition to the minimum payment. With this option you commit to paying the minimum monthly payment due plus a set amount extra each
              month.
            </p>
            <p>For example: minimum payment + twenty dollars</p>
          </div>
          <div class="col-md-12">
            <div class="form-row">
              <label for="balanceLabel">Additional Monthly Payment:</label>
              <div class="input-group">
                <span class="input-group-addon">$</span>
                <input type="number" min="0" data-number-to-fixed="2" data-number-stepfactor="100" class="form-control currency" id="additionalMonthlyPayment" onchange="Calculate(); " />
              </div>
            </div>
          </div>
          <div class="col-md-12">
            <h1 class="headers">First minimum payment:</h1>
            <div style="padding: 20px;">
              <span id="rate2" class="readonly"></span>
            </div>
          </div>
          <div class="col-md-12">
            <h1 class="headers">Total first monthly payment:</h1>
            <div style="padding: 20px;">
              <span id="totalMonthlyPayment" class="readonly"></span>
            </div>
          </div>
          <div class="col-md-12">
            <h1 class="headers">Payment Option #3: Fixed Payment</h1>
            <p>This option estimates how long it takes to pay off the credit card balance if you commit to paying a fixed amount each month. This means you set the amount you pay and do not change the amount as you pay your bill down.</p>
            <p>For example: pay $300 each month</p>
            <p>*Your fixed payment must be greater than or equal to your first minimum monthly payment.*</p>
          </div>
          <div class="col-md-12">
            <div class="form-row">
              <h1 class="headers">Fixed monthly payment:</h1>
              <div class="input-group-extended">
                <input type="number" min="0" data-number-to-fixed="2" data-number-stepfactor="100" class="form-control currency" id="rate3" />
              </div>
            </div>
          </div>

          <div class="col-md-12">
            <h1 class="headers">Your Payment Information:</h1>
            <div class="col-md-12" style="border: 1px dotted #000; padding: 10px;">
              <div class="col-md-12 float-left" style="background-color: #267cac; color: #FFF;">
                Current credit card balance:
              </div>
              <div class="col-md-12 float-left" style="background-color: #EEF5F5;">
                <span class="numberResult" id="balanceTxt"></span>
              </div>
              <div class="col-md-12 float-left" style="background-color: #267cac; color: #FFF;">
                APR (annual percentage rate):
              </div>
              <div class="col-md-12 float-left" style="background-color: #EEF5F5;">
                <span class="numberResult" id="aprTxt"></span>
              </div>
              <div class="col-md-12 float-left" style="background-color: #267cac; color: #FFF;">
                First minimum monthly payment:
              </div>
              <div class="col-md-12 float-left" style="background-color: #EEF5F5;">
                <span class="numberResult" id="firstMinimumPaymentTxt"></span>
              </div>
              <div class="col-md-12 float-left" style="background-color: #267cac; color: #FFF;">
                Additional monthly payment:
              </div>
              <div class="col-md-12 float-left" style="background-color: #EEF5F5;">
                <span class="numberResult" id="additionalMonthlyPaymentTxt"></span>
              </div>
              <div class="col-md-12 float-left" style="background-color: #267cac; color: #FFF;">
                Fixed Monthly Payment:
              </div>
              <div class="col-md-12 float-left" style="background-color: #EEF5F5;">
                <span class="numberResult" id="fixedMonthlyPaymentTxt">
                            </div>
                        </div>
                    </div>
                    <div class="col-md-12">
                        <h1 class="headers">Estimated Repayment Results</h1>
                        <table class="table">
                            <thead>
                            <tr>
                                <th scope="col"></th>
                                <th scope="col">Option #1: Minimum payment only	</th>
                                <th scope="col">Option #2: Minimum payment plus	</th>
                                <th scope="col">Option #3: Minimum payment plus	</th>
                            </tr>
                            </thead>
                            <tbody>
                            <tr>
                                <th scope="row">Time to pay off balance</th>
                                <td><span id="option1"></span><span id="years1"></span> </td>
                <td><span id="option2"></span><span id="years2"></span></td>
                <td><span id="option3"></span><span id="years3"></span></td>
                </tr>
                <tr>
                  <th scope="row">Original balance</th>
                  <td><span id="originalBalanceOption1"></span></td>
                  <td><span id="originalBalanceOption2"></span></td>
                  <td><span id="originalBalanceOption3"></span></td>
                </tr>
                <tr>
                  <th scope="row">Interest paid</th>
                  <td></td>
                  <td></td>
                  <td></td>
                </tr>
                <tr>
                  <th scope="row">Total paid</th>
                  <td></td>
                  <td></td>
                  <td></td>
                </tr>
                <tr>
                  <th scope="row">Amount saved</th>
                  <td></td>
                  <td></td>
                  <td></td>
                </tr>
                <tr>
                  <th scope="row">Time saved</th>
                  <td></td>
                  <td></td>
                  <td></td>
                </tr>
                </tbody>
                </table>
              </div>


            </div>
          </div>


        </div>
      </div>

    </div>

JSFiddle

谢谢

1 个答案:

答案 0 :(得分:0)

在调用while(1)循环之前,如果不满足某些条件,您的代码将生成一个无限循环。我建议添加类似的内容

if(!minimumPayment || !originalBalance || !interestRate){
    alert('please fill out all required fields');
//log values here so you know which aren't filled out
    return;
}

getPayments()函数的开头,因此如果其中任何一个值不返回truthy,它就不会执行该循环。这样,您将知道只有退出循环才能进入该循环(所有这些变量实际上都具有值)。