【问题标题】:Trouble with JS while loops and if statements :(JS while 循环和 if 语句的问题:(
【发布时间】:2021-07-25 05:37:42
【问题描述】:

我想要一个函数来选择一个随机数,并根据该数字选择一个全局变量并将其添加到一个数组中,重复 5 次。我不知道这个想法是否有效。它基本上是一个在线2D游戏,它需要随机选择一张卡片,然后有卡片的信息可用,所以在游戏后期卡片可以互相对抗。

我已经在谷歌上搜索了大约 2 个小时,但它仍然无法正常工作,我可能遗漏了一些明显或愚蠢的东西。

现在我在函数之外有一个空数组,然后选择一个随机数,我有 if 语句将对应于将放入数组中的正确卡片。我还希望稍后在其他函数中可以访问该数组,例如我必须在必须比较卡片的地方创建函数,所以我只需要随机选择 5 张卡片并保存它们的信息以用于后面的函数。(以后我会添加更多 else if 语句,因为总共有 16 张卡片)

<script src="https://randojs.com/1.0.0.js"></script>
<script>
    
    let centaur = { name:'Centaur', class:'Common', health:50, attack:25, defence:15, strength:10, magic:10, image:'images/Cards/2_Common/CENTAUR.png' };
    let dryad = {name:'Dryad', class:'Common', health:10, attack:10, defence:10, strength:10, magic:50, image:'images/Cards/2_Common/DRYAD.png'};
    /*let  = {name:'', class:'', health:, attack:, defence:, strength:, magic:, image:''};*/
    
    var listofran = {};
    
    function findcard(){
        var random = rando(0,6);
        while (let i=5; i>0;i--){
            if (random == 0){
            listofran.push = centaur;
            }
            else if (random ==1) {
            listofran.push = dryad;
            }
            else if (random ==2) {
            listofran.push = gryffin;
            }
            else if (random ==3) {
            listofran.push = giant;
            }
            else if (random ==4) {
            listofran.push = harpy;
            }
            else if (random ==5){
            listofran.push = satyr;
            }
            else{
            listofran.push = mermaid;
            }
        i--;

        }
    }
    
    document.getElementById('rand').innerHTML=listofran;
    
</script>

然后在正文中我只是想看看它是否有效,所以我只有这个只是为了看看我是否可以让列表出现。

<p>random list<span id="rand"></span></p>>

老实说,我一直在纠结哪些组件需要在哪些功能和位置中使用,所以是的,任何帮助都将不胜感激。

【问题讨论】:

  • listofran.push = centaur -> listofran.push(centaur)
  • listofran 是一个普通对象 ({}),它没有 push 方法。您可能想要使用数组:[];如果您将原始项目存储在数组中,您的 findcard 方法也可以减少到只有几行。然后你可以简单地这样做:Getting a random value from a JavaScript array
  • 哦!是的,我会试试谢谢
  • 数组可以保存对象,或者“让”事物。就像我可以制作一个类似于 cardarray = [centaur, dryad] 的数组,它从全局变量中获取信息吗?

标签: javascript html if-statement while-loop global-variables


【解决方案1】:

您可以从一系列生物中选择一个(伪随机)生物,而无需循环。将您的代码重构为minimal reproducable example

document.addEventListener("click", handle);

const creatures = [
  { name:'Centaur', },
  { name:'Dryad', },
  { name:'Gryffin', },
  { name:'Giant', },
  { name:'Harpy', },
  { name:'Satyr', },
  { name:'Mermaid', },
];

let listOfRan = [];

// the function tho tame the creatures
function findCard(){
  // next 2 lines are what the answer is all about
  const randomIndex = Math.floor(Math.random() * creatures.length);
  listOfRan.push(creatures[randomIndex]);
  
  // output for this example
  document.querySelector('#rand').textContent = `Last added: ${
    JSON.stringify(listOfRan.slice(-1)[0])}\n`;
  document.querySelector('#all').textContent = `All of listOfRan: ${
    JSON.stringify(listOfRan, null, 2)}\n`;
}

// Not specific for this answer
// Function to handle all events in document
function handle(evt) {
  if (evt.target.dataset.handleid === "1") {
    return findCard();
  }
  
  if (evt.target.dataset.handleid === "2") {
    return document.querySelectorAll("pre")
      .forEach( elem => elem.textContent = "");
  }
  
  if (evt.target.dataset.handleid === "3") {
    if (confirm(`Are you sure?`)) { 
      listOfRan = [];
      document.querySelector('#all').textContent = "Empty";
    }
    return;
  }
}
<button data-handleid="1">Random creature please</button>
<button data-handleid="2">Clear output</button>
<button data-handleid="3">Clear [listOfRan]</button>
<pre id="rand"></pre>
<pre id="all"></pre>

【讨论】:

  • 非常感谢。我能问一下,你为什么使用两个函数?能不能稍微解释一下,以便更好地理解它。
  • 另外,如果我在此部分添加更多按钮,如果 (evt.target.nodeName === "BUTTON") 将被激活,有没有办法重写它以使其针对特定按钮?跨度>
  • handle 函数用于事件委托部分。要定位特定按钮,您可以给它们一个唯一的 id 或数据属性。例如&lt;button data-clickme ...&gt; => if (evt.target.dataset.clickme) {...}
【解决方案2】:

你可以试试这个代码。您需要一个数组来保存值并在 for 循环中添加项目。

    
    let centaur = { name:'Centaur', class:'Common', health:50, attack:25, defence:15, strength:10, magic:10, image:'images/Cards/2_Common/CENTAUR.png' };
    let dryad = {name:'Dryad', class:'Common', health:10, attack:10, defence:10, strength:10, magic:50, image:'images/Cards/2_Common/DRYAD.png'};
    /*let  = {name:'', class:'', health:, attack:, defence:, strength:, magic:, image:''};*/
    
    
    var listofran = [];
    
    function findcard(){
        for (let i=5; i>0;i--)
        {
          var random = rando(0,6);
          if (random == 0){
            listofran.push(centaur);
          }
          else if (random ==1) {
            listofran.push(dryad);
          }
        }
    }
    findcard();
    document.getElementById('rand').innerHTML=listofran.map(x => x.name).join(',');
    
<script src="https://randojs.com/1.0.0.js"></script>
<p>random list</p><span id="rand"></span>

【讨论】:

    猜你喜欢
    • 2019-08-21
    • 2013-06-09
    • 2016-01-12
    • 2012-06-18
    • 2015-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-27
    相关资源
    最近更新 更多