简体   繁体   中英

How do I create a random property inside a randomly selected object?

For example, if I have:

var weapon = [ "sword", "mace", "staff"];

var swordtype = [ "long", "short"];

var stafftype = [ "quarter", "magic"];

and my script randomly selects 'Sword' to display in my HTML p tag from the weapon variable.

How can I say that if my code randomly selects "Sword" from the weapon variable, it will also randomly select a "swordtype" to go with it? Making the output either "long sword" or "short sword"?

You'll need to associate related data. So, your structure could be like this:

 // Use objects, not arrays to store key/value pairs var weapons = { sword:["long","short", "broad"], mace: ["standard", "long", "short"], staff: ["quarter", "magic", "wizard"], "nuclear missle": ["10 megaton", "20 megaton", "50 kiloton"], dagger: ["standard", "poison"] }; // Function for selecting random weapon function getRandomWeapon(){ // Choose random weapon as an index from the weapons object: var weaponNum = Math.floor(Math.random() * Object.keys(weapons).length); // Get the property name that corresponds to that key number: var weapon = Object.keys(weapons)[weaponNum]; // Choose random weapon type as an index from the random weapon selected above: var specificWeaponNum = Math.floor(Math.random() * weapons[weapon].length); // Get the array value associated with that index var specifcWeapon = weapons[Object.keys(weapons)[weaponNum]][specificWeaponNum]; return specifcWeapon + " " + weapon; } document.querySelector("button").addEventListener("click", function(){ document.getElementById("weapon").textContent = getRandomWeapon(); }); 
 <div>You have a: <span id="weapon"></span></div> <button>Get Weapon</button> 

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