例如,如果我有:
var weapon = [ "sword", "mace", "staff"];
var swordtype = [ "long", "short"];
var stafftype = [ "quarter", "magic"];我的脚本随机选择“剑”在我的HTML标记中显示在武器变量中。
如果我的代码随机地从武器变量中选择“剑”,它还会随机地选择一个“剑型”来配合它,我怎么说呢?输出“长剑”还是“短剑”?
发布于 2017-05-30 02:50:22
您需要关联相关数据。你的结构可能是这样的:
// 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>
https://stackoverflow.com/questions/44252500
复制相似问题