Nei*_*ler 5 javascript arrays random html-input
您好,我正在为学校做一个项目,我正在尝试从姓名列表中生成随机的姓名组。组的大小和组的数量将基于用户的输入。我有从数组中随机生成单个元素的代码,但我需要一些帮助分组。这是我到目前为止的代码。它无法运行请帮助谢谢
function yeah()
{
var arr = prompt("Enter your names").split(",")
console.log(arr);
var random = arr[Math.floor(Math.random() * arr.length)];
document.getElementById("h2").innerHTML = random;
}
function groups()
{
var arr = prompt("Enter your names").split(",");
var random = arr[Math.floor(Math.random() * arr.length)];
var numElem = document.getElementById("input2").value;
for (i=0;i <= arr.length; i++)
{
var newArr = [random];
console.log(newArr);
//print name to a new list
//remove name from old list
/* var arr = prompt("Enter your names").split(",")
var groupNum = document.getElementById("input1").value;
var newArrays = arr.length / groupNum; */
}
} Run Code Online (Sandbox Code Playgroud)
/* Reset */
* {
margin: 0;
padding: 0;
}
html,body {
height:100%;
margin:0;
font-family: 'Montserrat', 'sans-serif';
color:#424242;
overflow: hidden;
}
.display {
text-align: center;
display: table;
height:100%;
margin:0 auto;
}
.wrap {
display: table-cell;
vertical-align: middle;
}
p {
font-size: 50px; /* For lamers who don't support viewport sizing */
font-size:20vmin;
text-align: center;
margin: 0;
}
#h2 {
float: center;
font-size: 30vmin;
background-size: contain;
}
input.text-display {
display: inline-block;
color: #5E5E5E;
font: bold 20px arial;
text-decoration: none;
text-align: center;
margin: 20px auto;
padding: 15px 20px;
background: #EFF0F2;
border-radius: 4px;
border-top: 1px solid #F5F5F5;
box-shadow: inset 0 0 25px #E8E8E8, 0 1px 0 #C3C3C3, 0 2px 0 #C9C9C9, 0 2px 3px #333;
text-shadow: 0px 1px 0px #F5F5F5;
}
span.love {
display: block;
position: absolute;
bottom:10px;
width: 100%;
text-align: center;
}
span.love a {
text-decoration: none;
color:#D12026;
}
.twitter-follow-button {
vertical-align: text-bottom;
}
.twitter-share-button {
vertical-align: text-bottom;
}Run Code Online (Sandbox Code Playgroud)
<div class="display">
<div class="wrap">
<p>Your random value is:</p>
<div id="h2">Null</div>
<input class="text-display" type="button" onclick="yeah()" height="50px" width="50px" value="click to input data">
<!-- <input type="button" onclick="display()" value="display random"> -->
<br>
<input id="input1" value="Enter number of Groups">
<input id="input2" value="Enter number of elements per Group">
<input type="button" onclick="groups()">
</div>
</div>Run Code Online (Sandbox Code Playgroud)
这是第一个修复:要将新元素添加到数组(就像您在 for 循环中所做的那样),您应该使用 arr.push() 方法。在此之前,您还需要将 newArr 声明为空数组。
然而,我并不完全确定您在小组职能中是否正在做您打算做的事情。现在看起来您正在从列表中选择一个随机名称,然后根据列表中的名称多次将该随机名称分配给新数组。
可能对您有帮助的是写出您想要执行的步骤列表(我们称之为伪代码),然后将该列表转换为 JavaScript 代码。在该列表中发现不一致之处比筛选有时令人困惑的代码要容易得多。
希望这对您有所帮助,如果您还有其他问题,请告诉我!
| 归档时间: |
|
| 查看次数: |
2656 次 |
| 最近记录: |