亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

ReactJS 將 2 個數組轉換為表

ReactJS 將 2 個數組轉換為表

梵蒂岡之花 2023-05-19 15:58:50
我有 2 個數組,我想在表格中呈現它們。const arr1 = ["item1","item2","item3","item4"]const arr2 = ["price1","price2","price3","price4"]我想將其轉換為<table>    <tr>        <td>item1</td>        <td>price1</td>    </tr>    <tr>        <td>item2</td>        <td>price2</td>    </tr>    <tr>        <td>item3</td>        <td>price3</td>    </tr>    <tr>        <td>item4</td>        <td>price4</td>    </tr></table>注意:數組保證具有相同的長度。有人可以建議如何在 React 中動態完成此操作。
查看完整描述

2 回答

?
侃侃爾雅

TA貢獻1801條經驗 獲得超16個贊

您可以將所有行存儲在一個數組中,然后在以下位置使用它table:


export default function App() {

  const arr1 = ["item1","item2","item3","item4"]

  const arr2 = ["price1","price2","price3","price4"]

  const rows = []

  for (const [index, value] of arr1.entries()) {

    rows.push(

      <tr key={index}>

        <td>{value}</td>

        <td>{arr2[index]}</td>

      </tr>

    )

  }

  return (

    <div className="App">

      <table>

        <tbody>

          {rows}

        </tbody>

      </table>

    </div>

  );

}


查看完整回答
反對 回復 2023-05-19
?
溫溫醬

TA貢獻1752條經驗 獲得超4個贊

如果數組總是有相同的長度,你可以使用 map 或類似的東西。


<table>

{

   arr1.map((element, index) => <tr>

     // The first one is the nth element from the array

     // The second one we just access through index

        <td>{element}</td>

        <td>{arr2[index]}</td>

    </tr>

)

}

</table>


或者

<table>

{

   Array(arr1.length).map((element, index) => <tr>

          // We just access through index

          <td>{arr1[index]}</td>

          <td>{arr2[index]}</td>

     </tr>)

}

</table>


查看完整回答
反對 回復 2023-05-19
  • 2 回答
  • 0 關注
  • 159 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號