Search code examples
javascripthtmleaseljscreatejs

How to generate random library objects using createJS


I have several library objects ("s0, s1.... sn"), and I want to generate them randomly every time my for cycle loops.

Instead of having:

switch(Math.floor(Math.random() * n))
{
     case 0: 
          x = new lib.s0();
          break;
     case 1:
          x = new lib.s1();
          break;
     (...)
}

I want it like this;

x = new lib.s[Math.floor(Math.random() * n)]();

In ActionScript I used to do this, but it doesn't work in createJS

x = new (getDefinitionByName("s"+ Math.floor(Math.random() * n)) as Class)

So, how can I accomplish this in createJS ?


Solution

  • You can access a item of a object with a dynamic key like this:

    x = new lib['s' + Math.floor(Math.random() * n)]();