javascript - Javascript 我在 while 循环中有一个嵌套的 for 循环,它没有按预期工作
问题描述
我无法弄清楚为什么我的代码会无限运行。
var stateArray = ["CO", "AK", "CA", "KY", "NM"];
var selectedStates = [];
var important = 6
while (important < 9) {
let j = Math.floor(Math.random() * 4);
for (let i = 0; i < selectedStates.length;i++){
if (stateArray[j] == selectedStates[i]){
break;
} else {
selectedStates.push(stateArray[j]);
console.log(selectedStates);
important++
}
}
}
如果你能帮助我,那就太棒了。
解决方案
如果您想要选择 3 个随机状态,这就是您想要的
var stateArray = ["CO", "AK", "CA", "KY", "NM"];
var selectedStates = [];
var important = 6
while (important < 9) {
let j = Math.floor(Math.random() * 4);
selectedStates.push(stateArray[j]);
++important;
}
console.log(selectedStates)
或者,如果您不想重复,那么
var stateArray = ["CO", "AK", "CA", "KY", "NM"];
var selectedStates = [];
var important = 6
while (important < 9) {
let j = Math.floor(Math.random() * 4);
if (selectedStates.includes((stateArray[j]))) {
continue;
}
selectedStates.push(stateArray[j]);
++important;
}
console.log(selectedStates)
推荐阅读
- mysql - sql如何按条件添加值并放入特定列
- php - PHP 问题。我收到电子邮件,但没有来自网站的用户输入
- python - 分组功能优化
- java - java.io.EOFException:由于在检索数据时输入结束,没有要映射到对象的内容
- r - 视图中的错误:“名称”属性 [1] 必须与向量 [0] 的长度相同
- html - HTML5/CSS3:图像作为弹性项目
- ckan - 从外部 API 创建 CKAN 数据集并同步数据集
- ios - 我在哪里可以下载 WWDC2019 源代码?
- python - 有没有办法在 itertools.combinations() 中找到 nᵗʰ 条目而不将整个事物转换为列表?
- amazon-web-services - AWS 中国应用程序负载均衡器 ARN 无效