p5.js中访问数组元素返回undefined问题求助
Hey there! I see the issue you're running into—let's unpack this step by step.
The Root Cause: Execution Order in p5.js
In p5.js, code runs in a specific sequence:
- First, all global-level code (like your standalone
console.logstatements) executes immediately when the script loads. - Then, the
setup()function runs once, right after the page finishes initializing.
Your position array is indeed a global variable, but those console.log lines are running before setup() fills the array with values. At that early point, position is just an empty array ([]), so:
position.lengthreturns0position[1]returnsundefined(since there’s no second element to access yet)
How to Correctly Access the Array Elements
To ensure you’re accessing the array after it’s been populated, move your console.log statements inside the setup() function, right after the loop that adds values to the array. This way, you’ll only log the data once the array has all 10 random numbers.
Here’s your revised code:
let position = [] function setup() { createCanvas(400, 400); for (let i = 0; i < 10; i++) { let x = random(5, 10) position.push(x) } // Now the array is filled—safe to log and access elements! console.log(`The position array is ${position}`) console.log(`The length of the position array is ${position.length}`) console.log(`The second value in the position array is ${position[1]}`) } function draw() { background(200) text(`This is the implementation of random ${random(5,10)}`,10,10) // You can also access the array in draw if needed, e.g.: text(`Second element from position array: ${position[1]}`, 10, 30) }
Accessing Elements Later in Your Code
Since position is a global variable, you can access its elements from any other function (like draw() or a custom function you write) at any time after setup() has run. Just use the syntax position[index] where index is the zero-based number of the element you want (so position[0] is the first element, position[1] is the second, and so on).
内容的提问来源于stack exchange,提问作者James

