如何创建含div数组的嵌套数组?解决push覆盖问题及存储方案咨询
Hey there! Let's break down how to fix your array issue first, then talk about better data structure options for your click-to-display use case.
Fixing the Nested Array Setup
The problem with your current array[index][index].push(div) approach is likely that you haven't properly initialized the inner arrays first. If the inner array at array[index] doesn't exist yet, trying to push to it will cause errors, and using index assignment (like array[index][index] = div) will replace existing content instead of adding to it.
Here's the correct way to build your nested array:
// Step 1: Initialize the outer array with empty inner arrays as placeholders let divGroups = [[], []]; // First inner array for 5 divs, second for more // Step 2: Get your div elements (adjust the selector to match your HTML) const allDivs = document.querySelectorAll('.target-div'); // Step 3: Populate the inner arrays allDivs.forEach((div, index) => { if (index < 5) { // Add first 5 divs to the first group divGroups[0].push(div); } else { // Add remaining divs to the second group divGroups[1].push(div); } });
With this setup, divGroups[0] will hold your 5 divs, and divGroups[1] will hold the rest—no overwriting, just appending to the inner arrays as intended.
Better Data Structure Suggestions
Since you're building a system to display content on click, using objects (or an array of objects) can make your code more readable and maintainable, because you can add descriptive labels or metadata for each group.
Option 1: Object with Named Groups
If your groups have clear identities, use an object where each key represents a group:
let divCollections = { primarySet: [], // Holds the first 5 divs secondarySet: [] // Holds additional divs }; // Populate the object allDivs.forEach((div, index) => { if (index < 5) { divCollections.primarySet.push(div); } else { divCollections.secondarySet.push(div); } });
Option 2: Array of Objects (for Scalability)
If you might add more groups later, an array of objects lets you include extra info (like a display name or a button ID) directly with the divs:
let divGroups = [ { groupName: "First 5 Divs", buttonId: "show-first-group", elements: [] }, { groupName: "Additional Divs", buttonId: "show-second-group", elements: [] } ]; // Populate the elements allDivs.forEach((div, index) => { if (index < 5) { divGroups[0].elements.push(div); } else { divGroups[1].elements.push(div); } }); // Example: Attach click events dynamically using the object data divGroups.forEach(group => { document.getElementById(group.buttonId).addEventListener('click', () => { // Hide all divs first allDivs.forEach(div => div.style.display = 'none'); // Show only the current group's divs group.elements.forEach(div => div.style.display = 'block'); }); });
This approach keeps your group metadata and elements together, making it easier to extend if you add more groups down the line.
内容的提问来源于stack exchange,提问作者Dmitriy

