简体   繁体   中英

Javascript: How do I create a function that can generate an X amount of objects drawing from fixed amount of classes?

For my coding assignment, I'm tasked with creating a function that can generate an X amount of objects drawing from fixed amount of classes. But while the objects are being generated, I would like to store those objects in an array. How would I go about doing this in Javascript?

Pretty much the same as you would do for two objects. Just use the length of the array to pick a random element, and use a loop to perform the action X times:

 /* Class definitions */ function Animal(){ var a = document.createElement('div'); a.className = 'animal'; return a} function Horse(){ var a = new Animal(); a.className += ' horse'; return a } function Pig(){ var a = new Animal(); a.className += ' pig'; return a } function Rat(){ var a = new Animal(); a.className += ' rat'; return a } /* Variable definitions */ var animals = ['Horse', 'Pig', 'Rat'], output = document.getElementById('output'), numberOfDraws = 5, res = []; /* Auxiliary functions */ // Returns a random element from a given array function pickRandom(arr){ return arr[ Math.floor( Math.random()*arr.length ) ]; } /* Main script */ // Pick a random object 5 times, store it in 'res' and show it for(var i = 0; i < 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: To get an instance of the class, you can eval the class name. See the demo above.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM