首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >添加事件侦听器以滚动dice javascript

添加事件侦听器以滚动dice javascript
EN

Stack Overflow用户
提问于 2017-10-25 18:24:37
回答 5查看 450关注 0票数 0

我目前正在为课堂做一个初学者JavaScript程序。

程序应该向用户显示两个输入字段。第一个输入字段将接受一个整数,该整数将确定模具有多少边。第二个输入将接受一个整数,该整数将确定抛出模具的次数。

这些输入必须验证为仅为正数。当输入输入,用户单击输入字段外时,addEventListener('blur')将触发,模具将被“抛出”。这应该显示,例如,You rolled: 6, 2, 3, 5 for a total roll of 16

建议我们使用一个循环来执行骰子的“滚动”。当模糊事件发生时,应根据需要执行循环多次,并应显示单个滚动加上和。

我的问题是:

我将如何从模具被抛入数组的次数中存储输入值,然后循环该数组以显示每个骰子抛出的随机数以及总抛出数?这将在两个输入字段每次发生模糊事件时发生。

目前,我的程序只显示一个随机数字从模具侧的输入和投掷量的输入。对于此任务,我曾尝试使用for或while循环,但没有成功。这就是我现在所拥有的。

代码语言:javascript
复制
function dieInfo() {

  // temporary label to display # of sides
  var dieSideNum = document.getElementById('die-side-num');
  // convert string input into floating integer, 
  // if this doesnt create a number use 0 instead
  var getDieSide = parseFloat(dieSideQuant.value) || 0;
  // temporary label to display throw total
  var throwTotal = document.getElementById('throw-total');
  //convert string input into floating integer
  // if this doesnt create a number use 0 instead
  var getThrowTotal = parseFloat(throwQuant.value) || 0;

  // if die sides input or throw amount input is <= 0
  if (getDieSide <= 0 || getThrowTotal <= 0) {
    // display error for improper number of sides for die input
    dieSideNum.textContent = "Please enter valid Die sides";
    // display error for improper throw amount input
    throwTotal.textContent = "Please enter valid throw amount";
  } else {
    // use random function to store random number from die sides input
    throwRand = Math.floor(Math.random() * (1 + (getDieSide) - 1)) + 1;
    // test- display random number of sides for die
    dieSideNum.textContent = "Number of Sides on Die: " + throwRand;
    // test - display throw count
    throwTotal.textContent = " You threw " + getThrowTotal + "times";

  }
}

// retrieve id for for amount of sides on die
var dieSideQuant = document.getElementById('die-side-quant');
// fire the dieInfo function when the input element loses focus
dieSideQuant.addEventListener('blur', dieInfo);
// retrieve id for throw amount input
var throwQuant = document.getElementById('throw-quant');
// fire the dieInfo function when the input element loses focus
throwQuant.addEventListener('blur', dieInfo);
代码语言:javascript
复制
<h1 id="info-die"> How many sides on die? </h1>

<input type="number" min="0" id="die-side-quant" placeholder="# sides on die">

<h3 id="die-side-num"></h3>

<h1 id="info-throw-die"> Throw Amount? </h1>

<input type="number" min="0" id="throw-quant" placeholder="throw amount">

<h3 id="throw-total"></h3>

我现在拥有的参考图片

EN

回答 5

Stack Overflow用户

发布于 2017-10-25 18:56:50

要从模具被抛入数组的次数中存储输入值,请声明一个Array并使用.push方法。

代码语言:javascript
复制
// declare an Array variable
var dieThrows = [];

// use .push to store the value in the Array.
dieThrows.push(throwRand);

// or don't bother with the extra throwRand variable by doing it this way
dieThrows.push(Math.floor(Math.random() * (1 + (getDieSide) - 1)) + 1);

若要循环遍历数组,请使用.forEach方法或只对值进行迭代:

代码语言:javascript
复制
// doing it ES5-style:
dieThrows.forEach(function (throwResult, index, array) {
    console.log(throwResult); // display the random numbers for each die throw in the dev tools console
});

// doing it ES6-style:
dieThrows.forEach( (throwResult, index, array) => (console.log(throwResult)) );

// doing it old-school:
for (var i = 0; i < dieThrows.length; i += 1) {
    console.log(throwResult); // display the random numbers for each die throw in the dev tools console
}

要获得抛出的总数,只需访问数组的.length属性(因为要将每个抛出存储在数组中):

代码语言:javascript
复制
var totalThrows = dieThrows.length;
票数 2
EN

Stack Overflow用户

发布于 2017-10-25 18:40:16

代码语言:javascript
复制
var numRolls = 6;
var numRollTotal = 0;

for(var i = 0; i < numRolls; i++) //Here happens the for magic.
{
    //Write and store
}
//Write again

我故意留下了一些空白;)看你的代码,你就足够聪明了。这个不需要数组。

票数 0
EN

Stack Overflow用户

发布于 2017-10-25 18:42:07

你已经正确地识别了子问题!您可以参考以下内容:

代码语言:javascript
复制
window.onload = function() {
  document.getElementById('numThrows')
    .addEventListener('blur', function() {
      var numSides = parseInt(document.getElementById('numSides').value);
      var numThrows = parseInt(document.getElementById('numThrows').value);
      
      var randArr = [];
      for (var i = 0; i < numThrows; i++)
        // On each repetition, store a result into `randArr`
        randArr.push(1 + Math.floor(Math.random() * numSides));
      
      // Now display the results
      var results = document.getElementById('results');
      results.innerHTML = randArr.map(function(randNum, throwNum) {
        // Generate HTML markup for each result
        return '<div class="result">' +
          'Throw #' + (throwNum + 1) + '; ' + 
          'result: ' + randNum +
        '</div>';
      }).join('');
      
      
    });
};
代码语言:javascript
复制
<div>Note this example has no validation</div>
<input id="numSides" placeholder="sides" type="text"/>
<input id="numThrows" placeholder="throws" type="text"/>

<div id="results">
</div>

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46939585

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档