簡體   English   中英

循環遍歷一組對象?

[英]Loop through an array of objects?

我正在努力創建一個印花稅計算器。

目前,我有一個包含3個屬性的對象數組,每個對象具有相同的屬性名稱但值不同。

我試圖循環遍歷此數組,以便在單擊按鈕時將屬性1和2附加到表行,但是循環僅追加第一個對象屬性而不追加其他屬性。

我知道有類似的問題,但沒有一個有幫助。 我確信有一些我想念的簡單。

我還附上了一個img,以便更好地理解這個問題

在此輸入圖像描述

這是我的代碼

         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);
            }
        }

     }

那是因為你將“tableRow”的替換值分配回“tableRow”。 在第一次迭代之后,tableRow不再包含“{taxband}”,並且replace無效。

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

您應該添加一個中間變量:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM