Var / Array随机选择

时间:2017-10-25 06:46:34

标签: javascript

我是一个业余爱好者,我正在做一个侧面项目。我希望在这个变量列表的底部进行“随机”编码(它的作用是......数组对吗?)从每组变量中随机选择。我如何使这项工作?

    var flanks = [
    "Androxus-Flank",
    "Zhin-Flank",
    "Buck-Flank",
    "Evie-Flank",
    "Lex-Flank",
    "Maeve-Flank",
    "Skye-Flank",
    "Talus-Flank"

];

var frontline = [
    "Ash-Frontline",
    "Barik-Frontline",
    "Fernando-Frontline",
    "Inara-Frontline",
    "Makoa-Frontline",
    "Torvald-Frontline",
    "Ruckus-Frontline"

];

var damage = [
    "Bomb King-Damage",
    "Tyra-Damage",
    "Viktor-Damage",
    "Willo-Damage",
    "Kinessa-Damage",
    "Lian-Damage",
    "Sha Lin-Damage",
    "Strix-Damage",
    "Cassie-Damage",
    "Drogoz-Damage"

];

var support = [
    "Grohk-Support",
    "Grover-Support",
    "Mal'Damba-Support",
    "Pip-Support",
    "Jenos-Support",
    "Seris-Support",
    "Ying-Support"

];

$("#button").click(function() { 
    $("#flanks").text(flanks[Math.floor(Math.random() * flanks.8)]);
    $("#frontline").text(frontline[Math.floor(Math.random() * frontline.7)]);
    $("#damage").text(damage[Math.floor(Math.random() * damage.10)]);
    $("#support").text(support[Math.floor(Math.random() * support.7)]);
});

这是我正在建设的HTML;如果有人不介意校对。

<div class="container">

  <div class="panel panel-default">
  <div class="panel-heading">Basic Functioning Demo for 'The Unofficial Hi-Rez Paladins' Champion Roulette'
   </div>
  <div class="panel-body">
    <ul>
      <li><strong>Flank</strong>--<span id="flanks"></span></li>
      <li><strong>Frontline</strong>--<span id="frontline"></span></li>
      <li><strong>Damage</strong>--<span id=damage></span></li>
      <li><strong>Support</strong>--<span id="support"></span></li>
    </ul>
    </div>

    <div class="panel-footer">
      <a href="#" id="button" class="btn btn-primary btn-lg btn-block text-center">R o l l</a>
    </div>
  </div>

</div>
<img src="https://i.imgur.com/u9nFQuH.png" class="center"/>

2 个答案:

答案 0 :(得分:0)

如果您只是引用正确的数组

,这应该可行

例如:

$("#race").text(races[Math.round((Math.random() * 32))]);

没有比赛数组

尝试将种族改为侧翼

$("#race").text(flank[Math.round((Math.random() * 32))]);

查看这是否有效的简单方法是使用控制台日志

console.log(flank[Math.round((Math.random() * 32))]);

答案 1 :(得分:0)

  

我如何使这项工作?

乘数 更改为数组(本例中为race)长度,Math.round改为Math.floor,以便您不要得到undefined

$( "#race" ).text( races[ Math.floor( Math.random() * races.length ) ] );