简体   繁体   中英

Loop through an array of objects?

I am trying to create a stamp duty calculator.

Currently, I have an array of objects containing 3 properties, every object has the same property name but different values.

I am trying to loop through this array to append property 1 and 2 to a table row if a button is clicked, however the loop appends only the first object properties and not the others.

I know there have been similar queries but none of them have helped. I'm sure there is something simple I am missing.

I have also attached an img for a better understanding of the problem

在此输入图像描述

here is my code

         var taxbands = [
         {
             min: 0,
             max: 125000,
             percent: 0
         },
         {
             min: 125000,
             max: 250000,
             percent: 0.02
         },
         {
             min: 250000,
             max: 925000,
             percent: 0.05
         },
         {
             min: 925000,
             max: 1500000,
             percent: 0.1
         },
         {
             min: 1500000,
             max: null,
             percent: 0.12
         }
     ]

     var tableRow = "<tr><td>{taxband}</td><td>{percent}</td><td>{taxable}</td><td>{TAX}</td></tr>";

     $('#calculate').on('click', function calculateButton() {
        calculateStampDuty();
     })

     function calculateStampDuty() {

        var userInput = parseInt($("#input-value").val());

        for (i = 0; i < taxbands.length; i++) {
            if (userInput < 125000) {
                tableRow = tableRow.replace("{taxband}", taxbands[i].min + "-" + taxbands[i].max);
                $("#explained-table").append(tableRow);
            }
        }

     }

that's because you assign the replaced value of "tableRow" back to "tableRow". After the first iteration, tableRow doesn't contain "{taxband}" anymore, and replace has no effect.

tableRow = tableRow.replace("{taxband}", taxbands[i].min + "-" + taxbands[i].max);
                $("#explained-table").append(tableRow);

You should instead add an intermediate variable:

var myRow = tableRow.replace("{taxband}", taxbands[i].min + "-" + taxbands[i].max);
                $("#explained-table").append(myRow );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM