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

p5.js中draw阶段读取setup填充的Point实例返回undefined的原因

p5.js遍历数组返回undefined问题解答

核心原因

  • 你定义的a是二维数组,a[x]存储的是对应横坐标下所有纵坐标的Point实例数组,直接对a调用forEach遍历,拿到的每一项是第二层的数组,不是Point实例,自然无法读取x、y属性。
  • 你填充数组时x的步长为10,导致a是稀疏数组,索引仅包含0、10、20...590,中间大量位置为空,就算遍历逻辑正确,空位置也会返回undefined。

p5.js完全支持在setup运行阶段完成数组填充,你的填充逻辑本身没有问题,错误仅出在draw阶段的数组遍历方式。

修复方案

方案1:嵌套遍历二维数组

保持现有的二维数组填充逻辑,遍历的时候嵌套读取第二层数组的Point实例即可:

let a = [];
var scl = 10;

class Point {
  constructor(i, j) {
    this.x = i;
    this.y = j;
  }
}

function setup() {
  createCanvas(600, 600);
  for(x = 0; x < width; x += scl) {
    a[x] = [];
    for(y = 0; y < height; y += scl) {
      let p = new Point(x, y);
      a[x][y] = p;
    }
  }
}

function draw() {
  background(0);
  // 嵌套遍历二维数组
  a.forEach(yList => {
    yList.forEach(p => {
      rect(p.x, p.y, scl);
    })
  });
}

方案2:改为一维数组存储(推荐)

填充时直接将Point实例推入一维数组,避免稀疏数组和多层遍历的问题:

let a = [];
var scl = 10;

class Point {
  constructor(i, j) {
    this.x = i;
    this.y = j;
  }
}

function setup() {
  createCanvas(600, 600);
  for(x = 0; x < width; x += scl) {
    for(y = 0; y < height; y += scl) {
      let p = new Point(x, y);
      a.push(p); // 直接存入一维数组
    }
  }
}

function draw() {
  background(0);
  a.forEach(p => {
    rect(p.x, p.y, scl);
  });
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 22:27:00