【问题标题】:How to load N number of items from array at a time on button click如何在单击按钮时一次从数组中加载 N 个项目
【发布时间】:2020-09-09 09:15:07
【问题描述】:

我有一个对象数组:

const resourcesData = [
  {
    title: 'Title 01',
    description: 'Description for Title 01',
  },
  {
    title: 'Title 02',
    description: 'Description for Title 02',
  },
  {
    title: 'Title 03',
    description: 'Description for Title 03',
  },
  {
    title: 'Title 04',
    description: 'Description for Title 04',
  },
  {
    title: 'Title 05',
    description: 'Description for Title 05',
  },
];

目前使用模板文字将它们加载到 DOM 中:

function resourceTemplate(resource) {
  return `
    <div>
      <h2>${resource.title}</h2>
      <p>${resource.description}</p>
    </div>
  `;
}
function loadResources() {
  document.getElementById('resources').innerHTML = resourcesData
    .map(resourceTemplate)
    .join('');
}

当我一次加载所有这些时它可以工作。 如何一次只加载 2 个并且只在按钮单击时显示下一个 2?

为了显示 2 个项目,单击“加载更多”按钮,它将显示接下来的 2 个项目。 然后当它到达数组的末尾时,它将只显示一个,并且加载更多按钮将被隐藏。


根据要求更新我尝试过的内容 以前我尝试使用 for 循环首先对结果进行切片,如下所示:

console.log(resourcesData.length);
let result = [];

for (let i = 0; i < resourcesData.length; i += 2) {
  result = resourcesData.slice(i, i + 2);
  console.log(result);
}

我得到了 3 个数组,但我不确定如何跟踪在按钮单击时显示哪个数组。

【问题讨论】:

  • 你是怎么做到的?
  • 我用我试图达到的结果更新了这个问题,谢谢你的提问

标签: javascript arrays template-literals


【解决方案1】:

您可以使用splice 从数组中提取一定数量的元素:

const resourcesData = [{"title":"Title 01","description":"Description for Title 01"},{"title":"Title 02","description":"Description for Title 02"},{"title":"Title 03","description":"Description for Title 03"},{"title":"Title 04","description":"Description for Title 04"},{"title":"Title 05","description":"Description for Title 05"}];

function resourceTemplate(resource) {
  return `
    <div>
      <h2>${resource.title}</h2>
      <p>${resource.description}</p>
    </div>
  `;
}

function loadResources() {
  document.getElementById('resources').innerHTML += resourcesData
    .splice(0, 2) // <-----------------------------------------------------
    .map(resourceTemplate)
    .join('');
    
  if (resourcesData.length === 0) { btn.style.display = 'none'; }
}

btn.addEventListener('click', loadResources);
<div id="resources"></div>
<button id="btn">Load resources</button>

【讨论】:

  • 是否有优先于slice的偏好?
  • @evolutionxbox slice 只会复制数组的一些元素,通过拼接它们会从原始数组中删除。所以你不需要跟踪你在哪里,每次只显示元素 [0] 和 [1]。如果您不想修改原始数组切片将是一个不错的选择。
  • 是的,我认为 OP 并不关心将元素保留在数组中。如果他这样做了,那么我们只需要保留一个索引来知道我们在哪里并使用切片,确实
猜你喜欢
  • 1970-01-01
  • 2012-02-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多