gpt4 book ai didi

javascript - 从数组 Javascript 生成随机元素组

转载 作者:行者123 更新时间:2023-11-29 15:31:00 24 4
gpt4 key购买 nike

嗨,我正在为学校做项目,我正在尝试从名称列表中生成随机的名称组。群组大小和群组数量将基于用户输入。我有从数组中随机生成单个元素的代码,但我需要一些帮助进行分组。到目前为止,这是我的代码。它不工作请帮忙谢谢

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; */


}


}
  /* 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;
}
<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>

最佳答案

这是第一个解决方法:要将新元素添加到数组(就像您在 for 循环中所做的那样),您应该使用 arr.push() 方法。在此之前,您还需要将 newArr 声明为空数组。

但是,我不完全确定您在群组功能中是否按照您的意愿行事。现在看起来您正在从您的列表中选择一个随机名称,然后,在您的列表中有多少次名称,就将该随机名称分配给您的新数组。

可能对您有帮助的是只写出您要采取的步骤列表(我们称之为伪代码),然后将该列表转换为 javascript 代码。与筛选有时令人困惑的代码相比,在该列表中发现不一致要容易得多。

希望对您有所帮助,如果您还有其他问题,请告诉我!

关于javascript - 从数组 Javascript 生成随机元素组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34913193/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com