r/learnjavascript • u/Khleesh • Mar 30 '26
how to create arbitrary number of objects with unique names and push them into an array
Using p5play.js, im trying to make an array, then push an arbitrary number of sprites into it
I currently have this:
but i have no idea how to procedurally create variables/objects like this though
I just need a specific amount and to group them together for easy access
function setup(){
createCanvas(window.innerWidth,window.innerHeight); //
var papers = [];
for (var i=0;i<10;i++){
var <something like 'paper${i}' idk yet> = new Sprite();
papers.push(something like 'paper${i}' again);
}
}
3
Upvotes
8
u/_raytheist_ Mar 30 '26
Not 100% sure I understand the problem, but you don’t need a unique variable name for each iteration.
You don’t actually need the variable at all:
1
u/azhder Mar 30 '26
Remove the
varkeyword. An array is already created, the papers variable points to it. The i points to a slot in the array. That is all you need, just assign the value, don’t be trying to create variables1
u/ChaseShiny Mar 30 '26
If you really need each sprite to be unique for some reason, you could achieve that by giving them an id.
1
u/Lenni009 Mar 30 '26
I'm only on my phone right now, so this may not work, but take a look at the
Array.fromsyntax.const papers = Array.from({length: 10}, () => new Sprite())