首页 > 解决方案 > 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++
            }
        }
    }

如果你能帮助我,那就太棒了。

标签: javascript

解决方案


如果您想要选择 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)

推荐阅读