【问题标题】:Loop through first 3 item in array JavaScript(react) [duplicate]循环遍历数组JavaScript(react)中的前3项[重复]
【发布时间】:2021-11-19 09:27:14
【问题描述】:

例如我有 5 个项目:

const items = [
{id: 1, name: 'book', price: 50},
{id: 2, name: 'phone', price: 450},
{id: 3, name: 'fish', price: 80},
{id: 4, name: 'apple', price: 5},
{id: 5, name: 'pen', price: 2},
]

当我们像这样使用 map 方法时:

{items.map( item => (
 <div> {item.name} {item.price} </div>
)}

我们展示所有项目;

但我想只显示其中的 3 个项目

我该怎么做?(使用ma​​p方法或for方法或其他方法)

【问题讨论】:

标签: javascript reactjs loops for-loop


【解决方案1】:

您可以使用Array.slice

{items.slice(0,3).map( item => (
 <div> {item.name} {item.price} </div>
)}

const items = [
{id: 1, name: 'book', price: 50},
{id: 2, name: 'phone', price: 450},
{id: 3, name: 'fish', price: 80},
{id: 4, name: 'apple', price: 5},
{id: 5, name: 'pen', price: 2},
]

const first3Items = items.slice(0,3);
console.log(first3Items);

【讨论】:

  • @Andreas 对此感到抱歉,这是我的错误。我更新了它。感谢您的提醒。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-11-10
  • 2011-11-30
  • 2019-03-29
  • 2018-12-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多