2017-08-13 51 views
0

我有一個遍歷對象的函數。香草JavaScript - Object.keys(object).forEach只顯示最後一項

在HTML上,它應該在其自己的表格行中顯示對象中的每個鍵和值。

Object.keys(nutrients).forEach(function(key) { 
    const nutrientsList = nutrients[key]; 

    nutritionTable.innerHTML = `<tr> 
            <td>${[ nutrientsList.label ]}</td> 
            <td>${[ nutrientsList.quantity ]} ${[ nutrientsList.unit ]}</td> 
           </tr>` 
}); 

當console.log顯示如預期的那樣,但在HTML上覆蓋了所有先前的元素並僅顯示最後一個元素。

DEMO

如何才能提高代碼並得到正確的結果呢?

回答

0

您將在每次迭代中替換整個HTML內容。我假設你想每次追加。爲此,請改用.insertAdjacentHTML()

Object.keys(nutrients).forEach(function(key) { 
    const nutrientsList = nutrients[key]; 

    nutritionTable.insertAdjacentHTML(
     "beforeend", 
     `<tr> 
      <td>${[ nutrientsList.label ]}</td> 
      <td>${[ nutrientsList.quantity ]} ${[ nutrientsList.unit ]}</td> 
     </tr>`); 
}); 

這是因爲任何形式.innerHTML分配的附加來自現有的HTML新的內容,包括+=的優選方式,增加任何新內容之前將破壞現有的DOM。這會產生不良的副作用。


順便說一句,因爲你使用ECMAScript 2015年的功能,你可能要考慮一個for-of循環。

for (const nutrientsList of Object.values(nutrients)) { 
    nutritionTable.insertAdjacentHTML(
     "beforeend", 
     `<tr> 
      <td>${[ nutrientsList.label ]}</td> 
      <td>${[ nutrientsList.quantity ]} ${[ nutrientsList.unit ]}</td> 
     </tr>`); 
} 
0

在每次更改nutritionTable的innerHTML的值迭代(所以你實際上覆蓋該值在每次循環迭代和最終值是最後一次迭代的在循環的值)。通過y覆蓋x值: -

相反,你可以使用+=追加該值:

Object.keys(nutrients).forEach(function(key) { 
    const nutrientsList = nutrients[key]; 

    nutritionTable.innerHTML += `<tr> 
            <td>${[ nutrientsList.label ]}</td> 
            <td>${[ nutrientsList.quantity ]} ${[ nutrientsList.unit ]}</td> 
           </tr>` 
}); 
1
  • x = y

  • x += y(或x = x+y):追加y值的x當前值。

然後:

nutritionTable.innerHTML += `<tr>....` // append 

而且不

nutritionTable.innerHTML = `<tr>....` // override