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

TypeScript动态初始化二维数组后赋值报错:Cannot set property of undefined

Fixing "Cannot set property of undefined" When Assigning DOM Elements to a 2D Array

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:04:10