javascript - JSX map 中的分隔符使用索引

标签 javascript reactjs

我想跳过 <hr />最后,所以我添加了使用索引和数组长度的条件,就像这样

{item.persons.map((item,i) => 
    <div>
        <p>Name: {item.name}</p>
    {i !== item.persons.length ? <hr /> : ''}
    </div>
)}

知道为什么这行不通吗?我可以离开 <hr />像这样

{item.persons.map((item,i) => 
    <div>
        <p>Name: {item.name}</p>
    <hr />
    </div>
)}

但这看起来很糟糕,因为它在最后一项之后也有 hr。

最佳答案

您应该记住,最后一项不是索引为length 的,而是length-1

var persons = ["A", "B", "C"]

{persons.map((item,i) => 
   {i !== (persons.length-1) ? console.log(item) : console.log("LAST")}
)}

关于javascript - JSX map 中的分隔符使用索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42199192/

相关文章:

javascript - react : Cannot access index of an array in a state (index undefined)

javascript - 我可以创建一个在删除输入文本时触发的事件吗?

javascript - 使用 ko.mapping.fromJS 保留原始值

javascript - 函数 insertMany() 无序 : proper way to get both the errors and the result?

javascript - react 路由器 v6 : get path pattern for current route

python - 通过 Flask-Python 为 React 生产应用程序(本地服务器)提供服务

reactjs - React Swiper Navigation 不工作怎么工作呢?

javascript - AngularJS 1.2 到 1.3 clientWidth 不再正确

javascript - 函数 Empty() {} 在哪里?

javascript - React Router 和 Semantic UI React 的问题