cariboni
cariboni

Reputation: 21

object name dynamic create

i have a single question,

i have this JS.

Scene.platform = new MenuItem();
Scene.platform.init(...code...);

this works fine, but i have N platforms, how i creat dynamic?

i tryed :

for(i=0....){

Scene.platform+i = new MenuItem();  
or
Scene.platform.i = new MenuItem();

}

i need the result like that:

Scene.platform1 = new MenuItem();
Scene.platform2 = new MenuItem();
Scene.platform3 = new MenuItem();

its possible? thanks in advance.

Upvotes: 0

Views: 18

Answers (3)

Suren Srapyan
Suren Srapyan

Reputation: 68635

For dynamic names you can use [] syntax.

Scene['platform' + i] = new MenuItem(); 

Example

const Scene = {};

for(let i = 0; i < 3; i++) {
  Scene['platform' + i] = {};
}

console.log(Scene);

But think about to use array instead of object and push your items into that array. Then you can use indexes to get , for example, first item via [0], which in your object style can be named like platform0.

const Scene = { platforms: [] };

for(let i = 0; i < 3; i++) {
  Scene.platforms.push({});
}

console.log(Scene.platforms[0]);

Upvotes: 1

David
David

Reputation: 218808

Any time you have variables like this:

platform1
platform2
platform...
platformN

What you really want is an array. Give your object an array called platforms, then you can store your "platforms" in that array. For example, if you have this:

Scene.platforms = [];

Then you can push elements to it:

for (var i = 0; i < someAmount; i++) {
    Scene.platforms.push(new MenuItem());
}

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1074038

Use an array:

Scene.platforms = [];
for (var i = 0; i < count; ++i) {
    Scene.platforms.push(new MenuItem());
}

Later, to access them, either loop through the array (see my other answer here) or index into it. E.g., if you want the first one:

Scene.platforms[0].doSomething();

Upvotes: 1

Related Questions