You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript数组对象分页循环重复显示:如何无需for...of实现无重复遍历?

数组分页显示问题解决

问题描述

我有一个对象数组:

let myArray = [
    {myParagraph: "This is paragraph 1"},
    {myParagraph: "This is paragraph 2"},
    {myParagraph: "This is paragraph 3"},
    {myParagraph: "This is paragraph 4"},
    {myParagraph: "This is paragraph 5"},
]

我希望遍历并分页显示这些对象,为此编写了如下代码:

let page = 1;
let button_number = 1;

let first_element_shown = 0;
let last_element_shown = 10;

let number_of_pages = Math.ceil(myArray.length / 10);

for (let i of myArray) {
    for (let j = 0; j < number_of_pages; j++) {
        for (let k = first_element_shown; k < last_element_shown; k++) {
            let card = document.createElement('div')
            let myParagraph = document.createElement('p');
            myParagraph.innerText = i.myParagraph;
            card.appendChild('myParagraph')
            document.getElementById("example_DIV").appendChild(card);
           }
    }
}

但这段代码会重复显示同一对象,请问如何不使用for (let i of myArray)语句,实现无重复地遍历数组并完成分页显示?


解决方案

问题根源

你嵌套了三层循环:外层遍历每个数组元素,中层遍历所有页码,内层遍历每页的10个位置,导致每个元素被重复渲染总页数×10次,这就是重复显示的核心原因。

正确实现代码

直接通过计算每页的索引区间,用普通for循环遍历对应位置的数组元素即可,完全不需要外层的for...of循环:

const pageSize = 10; // 每页显示的元素数量
const totalPages = Math.ceil(myArray.length / pageSize);
const container = document.getElementById("example_DIV");

// 渲染指定页码的内容
function renderPage(pageNum) {
    container.innerHTML = ""; // 先清空容器,避免新旧内容叠加
    // 计算当前页的起始和结束索引
    const startIndex = (pageNum - 1) * pageSize;
    const endIndex = Math.min(startIndex + pageSize, myArray.length);
    
    // 遍历当前页对应的数组区间
    for (let k = startIndex; k < endIndex; k++) {
        const card = document.createElement('div');
        const myParagraph = document.createElement('p');
        myParagraph.innerText = myArray[k].myParagraph;
        card.appendChild(myParagraph); // 注意这里要传DOM对象,不是字符串
        container.appendChild(card);
    }
}

// 初始渲染第一页
renderPage(1);

额外说明

  1. 计算结束索引时用Math.min,是为了避免当最后一页元素不足10个时,索引超出数组长度导致报错。
  2. 原代码里的card.appendChild('myParagraph')是错误的,应该传入创建好的DOM节点myParagraph,不是字符串。
  3. 如果需要做分页切换功能,可以基于totalPages生成页码按钮,点击按钮时调用renderPage并传入对应页码即可。

内容的提问来源于stack exchange,提问作者user21194080

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 01:20:17