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

p5.js中For循环创建数组后访问元素返回undefined问题求助

Why does position[0] return undefined in my p5.js code?

Hey there, let’s break down why you’re seeing undefined when trying to log position[0]—it all boils down to execution order in p5.js.

The Root Cause

In p5.js, the setup() function is automatically called after the library finishes initializing. But your console.log(position[0]) is sitting in the global scope, which means it runs immediately when your script loads—before setup() has even executed. At that point, your position array is still empty (you haven’t pushed any values into it yet), so trying to access index 0 naturally returns undefined.

Also, a quick side note: your for loop uses an undeclared i variable, which creates a global variable. It’s better to declare it with let to keep your scope clean and avoid unintended bugs.

The Fix

Move your console.log inside the setup() function, right after you’ve finished populating the position array. That way, the array will have values when you try to log the first element.

Here’s the corrected code:

let position = [];

function setup(){
  let cnv = createCanvas(window.width, window.height);
  cnv.parent('canvas');
  noStroke();
  
  // Declare i with let to avoid global scope pollution
  for(let i = 0 ; i < 10 ; i++){
    let x = random(10, 20);
    position.push(x);
  }
  
  // Now position has values—log the first element here
  console.log(position[0]);
}

function draw(){
  background('#fac81f');
  translate(width/2, height/2);
  ellipse(0, 0, width/3);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.16/p5.min.js"></script>

Now when you run this, console.log(position[0]) will print a valid random number from your array, since it runs after the array is filled in setup().

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 03:19:26