arrays - Javascript: How do I create a function that can generate an X amount of objects drawing from fixed amount of classes? -
for coding assignment, i'm tasked creating function can generate x amount of objects drawing fixed amount of classes. while objects being generated, store objects in array. how go doing in javascript?
pretty same 2 objects. use length of array pick random element, , use loop perform action x times:
/* class definitions */ function animal(){ var = document.createelement('div'); a.classname = 'animal'; return a} function horse(){ var = new animal(); a.classname += ' horse'; return } function pig(){ var = new animal(); a.classname += ' pig'; return } function rat(){ var = new animal(); a.classname += ' rat'; return } /* variable definitions */ var animals = ['horse', 'pig', 'rat'], output = document.getelementbyid('output'), numberofdraws = 5, res = []; /* auxiliary functions */ // returns random element given array function pickrandom(arr){ return arr[ math.floor( math.random()*arr.length ) ]; } /* main script */ // pick random object 5 times, store in 'res' , show for(var = 0; < numberofdraws; i++){ res.push( eval('new ' + pickrandom(animals) + '()') ); output.appendchild( res[i] ); }
.animal{float:left;padding:40px;background-size:100%}.horse{background-image:url(https://pbs.twimg.com/profile_images/587037647966613504/mk5oeksb.png)}.pig{background-image:url(https://33.media.tumblr.com/avatar_c2b180faa484_128.png)}.rat{background-image:url(http://38.media.tumblr.com/avatar_614c66cef635_128.png)}
<pre id="output"></pre>
edit: instance of class, can eval
class name. see demo above.
Comments
Post a Comment