猿问

ReactJS 将 2 个数组转换为表

我有 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 中动态完成此操作。


梵蒂冈之花
浏览 122回答 2
2回答

侃侃尔雅

您可以将所有行存储在一个数组中,然后在以下位置使用它table:export default function App() {&nbsp; const arr1 = ["item1","item2","item3","item4"]&nbsp; const arr2 = ["price1","price2","price3","price4"]&nbsp; const rows = []&nbsp; for (const [index, value] of arr1.entries()) {&nbsp; &nbsp; rows.push(&nbsp; &nbsp; &nbsp; <tr key={index}>&nbsp; &nbsp; &nbsp; &nbsp; <td>{value}</td>&nbsp; &nbsp; &nbsp; &nbsp; <td>{arr2[index]}</td>&nbsp; &nbsp; &nbsp; </tr>&nbsp; &nbsp; )&nbsp; }&nbsp; return (&nbsp; &nbsp; <div className="App">&nbsp; &nbsp; &nbsp; <table>&nbsp; &nbsp; &nbsp; &nbsp; <tbody>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {rows}&nbsp; &nbsp; &nbsp; &nbsp; </tbody>&nbsp; &nbsp; &nbsp; </table>&nbsp; &nbsp; </div>&nbsp; );}

温温酱

如果数组总是有相同的长度,你可以使用 map 或类似的东西。<table>{&nbsp; &nbsp;arr1.map((element, index) => <tr>&nbsp; &nbsp; &nbsp;// The first one is the nth element from the array&nbsp; &nbsp; &nbsp;// The second one we just access through index&nbsp; &nbsp; &nbsp; &nbsp; <td>{element}</td>&nbsp; &nbsp; &nbsp; &nbsp; <td>{arr2[index]}</td>&nbsp; &nbsp; </tr>)}</table>或者<table>{&nbsp; &nbsp;Array(arr1.length).map((element, index) => <tr>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // We just access through index&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <td>{arr1[index]}</td>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <td>{arr2[index]}</td>&nbsp; &nbsp; &nbsp;</tr>)}</table>
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答