如何使列表打印5个相同句子的随机数?

时间:2017-10-03 03:52:21

标签: javascript html

我需要像这样打印5行......

var lastName = document.querySelectorAll('div.lastname');
console.log(lastName);

但是我需要确保每行的数字不同。例如:

I just burped 5 times.
I just burped 5 times.
I just burped 5 times.
I just burped 5 times.
I just burped 5 times.

我现在的代码看起来像这样

I just burped 5 times.
I just burped 7 times.
I just burped 1 times.
I just burped 9 times.
I just burped 6 times.

任何人都可以帮忙吗?

3 个答案:

答案 0 :(得分:3)

在for循环中移动随机数生成器。

e.g。



function myFunction() {
  let text = " ";
  for (let i = 0; i < 5; i++) {
    let x = Math.floor((Math.random() * 10) + 1);
    text += "The number of times I just burped is " + x + "<br><br>";
  }
  document.getElementById("same").innerHTML = text;
}
&#13;
<h3 style="position: absolute;left:118px;top: 88px;" onClick="myFunction()"><button onclick="myFunction()"> Click Me </button></h3>

<div id="same"></div>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

将x赋值放在循环中。这样它每行都会改变。

<h3 style="position: absolute;left:118px;top: 88px;"
    onClick="myFunction()"><button onclick = "myFunction()"> Click Me </button></h3>  
    <div id="same"></div>
    <script>
       function myFunction() {
            var text= " ";
            var i;
            for(i=0; i<5; i++){
                        var x = Math.floor((Math.random() * 10) + 1);

                text += "The number of times I just burped is " + x +"<br><br>";
            }
            document.getElementById("same").innerHTML = text ;  
        }    
    </script> 

祝你好运!

答案 2 :(得分:1)

您可以创建一个数组,使用.slice()复制数组,使用.splice()从数组中删除一个元素,以便在结果中设置数字,该数字不是先前从数组中删除的数字的副本

<h3 style="position: absolute;left:118px;top: 88px;" onClick="myFunction()"><button onclick="myFunction()"> Click Me </button></h3>
<div id="same"></div>
<script>
  function myFunction() {
    var x = [0,1,2,3,4,5,6,7,8,9];
    var text = " ";
    var i;
    for (i = 0, copy = x.slice(); i < 5; i++) {
      text += "The number of times I just burped is " 
              + copy.splice(Math.floor(Math.random() * copy.length), 1)[0] 
              + "<br><br>";
    }
    document.getElementById("same").innerHTML = text;
    delete copy;
  }
</script>