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

JavaScript二维数组场景报错Cannot Set Property '0' of undefined求助

JavaScript报错Cannot Set Property '0' of undefined解决方案

问题根因

你代码的核心问题是所有自定义构造函数调用时都没有加new关键字,在ES5严格模式下,未使用new调用构造函数时,函数内部的this会被绑定为undefined,对undefined的属性赋值就会触发你遇到的类型错误。就算非严格模式下不直接报错,也会导致所有实例的属性都挂载到全局对象上,污染全局变量且逻辑完全不符合预期。

具体修复方案

给所有构造函数的调用位置补全new关键字即可,修复后的完整代码如下:

function Vector2(x, y)
{
  this.x = x;
  this.y = y;
  
  return this;
}

function Pixel(x, y, darkness)
{
  this.position = new Vector2(x, y);
  this.darkness = darkness;
  
  this.rgbDarkness = this.darkness * 255;
  
  return this;
}

function DataTexture2D(offsetX, offsetY, width, height)
{
  this.offset = new Vector2(offsetX, offsetY);
  this.size = new Vector2(width, height);
  
  this.pixels = [];
  
  for (var x = 0; x < width; x++)
  {
    this.pixels[x] = [];
    for (var y = 0; y < height; y++)
    {
      this.pixels[x][y] = new Pixel(x + this.offset.x, y + this.offset.y, 0.5);
    }
  }
  
  return this;
}

var test = new DataTexture2D(100, 50, 200, 300);

console.log(test.offset.x);

修复后代码可正常运行,控制台会输出预期值100,该写法完全兼容ES5标准,不需要做其他调整。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 19:09:04