Here is an explanation:
let position = []
// This code only _declares a function called setup. It
// does not run the function.
function setup() {
let cnv = createCanvas(window.width,window.height);
cnv.parent('canvas')
noStroke()
for(i = 0 ; i < 10 ;i++){
let x = random(10,20)
position.push(x)
}
}
// At this point, you have not added anything to
// position. It's a blank array, because `setup` has
// not been run.
console.log(position[0])
A solution might be to put your console.log
inside the setup
function.
let position = []
function setup() {
for(i = 0 ; i < 10 ;i++){
let x = random(10,20)
position.push(x)
}
console.log(position[0])
let cnv = createCanvas(window.width,window.height);
cnv.parent('canvas')
noStroke()
}
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>
This way it only runs when setup
is actually run.
13
solved For loop within p5.js and accessing array [closed]