[英]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()
函數中。 這就是重點。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.