简体   繁体   English

Javascript 我在 while 循环中有一个嵌套的 for 循环,但它没有按预期工作

[英]Javascript I have a nested for loop in a while loop and it's not working as expected

I can't figure out why my code is going infinitely.我不明白为什么我的代码会无限运行。

 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++
            }
        }
    }

If you could help me that would be amazing.如果你能帮助我,那就太棒了。

This is what you want if you want 3 random states selected如果您想要选择 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)

Or if you don't want duplicates then或者,如果您不想重复,则

 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)

What it seems is:看起来是这样的:

You're in the rounds of while loop.您正处于 while 循环中。

you didn't push anything in the selectedStates array yet, so how this for loop statement can be true i < selectedStates.length when i is already assigned 0 , and length of selectedStates is 0 as well.你没有推什么都selectedStates阵列还,所以如何for循环语句可以是真实的i < selectedStates.length时, i已经被分配0 ,而长度selectedStates0为好。

and this while loop statement important < 9 is always true because it's not getting increased from 6 .并且这个 while 循环语句important < 9总是正确的,因为它没有从6增加。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM