2017-05-30 95 views
0

例如,如果我有:如何在隨機選擇的對象內創建一個隨機屬性?

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

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

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

和我的腳本隨機選擇「劍」在從武器可變我的HTML p標籤來顯示。

我怎麼能說如果我的代碼從武器變量中隨機選擇了「劍」,它也會隨機選擇一個「劍形」來配合它呢?使輸出成爲「長劍」還是「短劍」?

+0

'武器= {劍: 「長」, 「短」],鐗: 「重」, 「輕」],工作人員:[「四分之一」,「魔術」}?或者'[{type:「sword」,subtypes:[「long」,「short」]},{type:「staff」,subtypes:[「quarter」,「magic」]}]'。或者是其他類似的結構,其中每一類武器的變體都與其直接相關。 – nnnnnn

回答

0

您需要關聯相關數據。所以,你的結構可能是這樣的:

// 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>

+0

這正是我所尋找的。非常感謝! – evolvingsymmetry