如何在随机选择的对象中创建随机属性?

时间:2017-05-30 02:23:42

标签: javascript jquery html

例如,如果我有:

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

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

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

我的脚本随机选择'Sword'来显示我的HTML p标签中的武器变量。

我怎么能说如果我的代码从武器变量中随机选择“Sword”,它还会随机选择一个“剑型”来配合它?输出要么是“长剑”还是“短剑”?

1 个答案:

答案 0 :(得分: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>