访问数组给出 undefined p5.js

Accessing array give undefined p5.js

这是我第二次尝试回答这个问题,希望我能更清楚地了解我的问题。我有一个初始 p5.js 设置:

// Setup empty array (I beleive 'position' this is in the global scope?)
let position = []
//p5 setup
function setup(){
  createCanvas(400,400)
  // Simple for loop to create an array of floating random numbers between 5 and 10 using the p5.js random function
  for(let i = 0; i < 10 ; i++){
    let x = random(5,10)
    position.push(x)
  }
}
function draw(){
  background(100)
  text(`This is the implementation of random ${random(5,10)`,10,10)
}
// Loging position unless I am mistaken, does NOT show the array
console.log(position)
// But trying to access an specific value within the array gives an 'undefined'
console.log(position[1])
// Undefined

如何访问单个值?

let position = []

function setup() {
  createCanvas(400, 400);
  for (let i = 0; i < 10; i++) {
    let x = random(5, 10)
    position.push(x)
  }
}
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)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.16/p5.js"></script>

请理解代码执行的顺序。考虑这个基本示例:

console.log('one');

function setup(){
  console.log('two');
}

function draw(){
  console.log('three');
}

加载您的代码时,会发生这种情况:

  • 第一个 console.log() 语句是 运行 并打印 'one'
  • setup() 函数已 定义 但尚未 运行。
  • draw() 函数已 定义 但尚未 运行。
  • 稍后调用setup()draw()函数。

现在考虑这个例子,它更接近你所拥有的:

function setup(){
  console.log('two');
}

console.log('one');

function draw(){
  console.log('three');
}

当您运行此代码时,会发生以下情况:

  • setup() 函数已 定义 但尚未 运行。
  • console.log('one') 语句是 运行 并打印 'one'
  • draw() 函数已 定义 但尚未 运行。
  • 稍后调用setup()draw()函数。

换句话说,在 P5.js 库自动调用这些函数之前,您在函数 运行 之外的代码。在您的情况下,您是 运行 在向数组添加任何内容之前访问数组的代码。

要解决此问题,请将代码移到 setup() 函数中。这就是它的全部意义。