TypeScript动态初始化二维数组后赋值报错:Cannot set property of undefined
Hey Brian, let's break down why you're hitting that error and how to fix it right away.
The Root Cause
Your code initializes gridArray as an empty 1D array (let gridArray: any [][] = []), but you never set up the nested arrays for each row. When you try to run gridArray[element.layout.row][element.layout.column] = e, gridArray[element.layout.row] doesn't exist yet—it's undefined. You can't set a property on an undefined value, which is exactly why that error pops up.
Solution 1: Pre-Initialize Rows (Best for Known Dynamic Sizes)
Since you already have the size details in gridArrayNumbers, you can pre-create all the row arrays first. Here's how to adjust your code:
let gridArrayNumbers = []; section.Layout.forEach(layout => { gridArrayNumbers.push(layout); // Ends up containing your row/column data, e.g., {row:2, column:3} }); // First, calculate the maximum row and column indices you'll need const maxRow = Math.max(...gridArrayNumbers.map(item => item.row)); const maxCol = Math.max(...gridArrayNumbers.map(item => item.column)); // Properly initialize the 2D array let gridArray: any[][] = []; for (let i = 0; i <= maxRow; i++) { // Create an empty array for each row (you can pre-fill with undefined if needed) gridArray[i] = []; } // Now assign your DOM element safely let e = document.createElement("label"); e.textContent = element.content; gridArray[element.layout.row][element.layout.column] = e;
Solution 2: Dynamically Create Rows On-the-Fly
If you don't want to pre-calculate dimensions upfront, you can check if the row exists right before assigning the column:
let gridArray: any[][] = []; // When assigning your DOM element: let e = document.createElement("label"); e.textContent = element.content; // Check if the row array exists—if not, create it if (!gridArray[element.layout.row]) { gridArray[element.layout.row] = []; } // This won't throw an error now gridArray[element.layout.row][element.layout.column] = e;
Both methods work great—pre-initializing is cleaner if you know the dimensions ahead of time, while dynamic creation is more flexible if rows are added unpredictably.
内容的提问来源于stack exchange,提问作者BrianM

