【问题标题】:Why is this simple .js for loop stopping after one iteration?为什么这个简单的 .js for 循环在一次迭代后停止?
【发布时间】:2016-02-25 14:36:00
【问题描述】:

我正在尝试制作一个简单的 .js 小程序,它会随机化一组英语单词,以便我可以将它们翻译成俄语对应的词:

var vocab_array_1 = ["end/distance", "hour/o'clock", "voice/vote", "city", "water", "table", "child", "force/strength", "father", "woman"];

for (var i = 0; i < vocab_array_1.length + 3; i++){
    var random_index = vocab_array_1[Math.floor(Math.random() * vocab_array_1.length)];

/*random_array.push(random_index);*/
    var random_array = [];
    random_array[i] = random_index;
}

但它只是在一次迭代后返回 random_array[i] 的结果。您可以看到我尝试使用 .push() 方法构建一个新数组,但意识到该方法返回数组并因此停止 for 循环。

删除后,我无法弄清楚为什么 for 循环在一次通过后停止运行。

注意:我确信 javascript 有随机化数组的方法;我正在尝试编写一种用于学习目的的方法。

编辑:

我执行了建议的更改,但无法将随机数组记录到控制台。这是修改后的代码:

var vocab_array_1 = ["end/distance", "hour/o'clock", "voice/vote", "city", "water", "table", "child", "force/strength", "father", "woman"];
var random_array = [];

for (var i = 0; i < vocab_array_1.length + 3; i++){
    var random_index = vocab_array_1[Math.floor(Math.random() * vocab_array_1.length)];
    random_array.push(random_index);
}

console.log(random_array);

【问题讨论】:

    标签: javascript arrays


    【解决方案1】:

    移动这条线

    var random_array = [];
    

    到顶部,因为它在每一轮都会被初始化。

    【讨论】:

      【解决方案2】:

      你的代码应该是这样的

      var vocab_array_1 = ["end/distance", "hour/o'clock", "voice/vote", "city", "water", "table", "child", "force/strength", "father", "woman"];
      
      var random_array = [];
      
      for (var i = 0; i < vocab_array_1.length + 3; i++){
          var random_index = vocab_array_1[Math.floor(Math.random() * vocab_array_1.length)];
          random_array.push(random_index);    
          //random_array[i] = random_index;
      }
      

      在循环之外初始化数组。

      【讨论】:

      • 谢谢!我进行了这些更改,但随后尝试 console.log(random_array);在 for 循环之外,一无所获。那是怎么回事?
      • 你在for循环后面加了console.log吗?
      【解决方案3】:

      如上一个回答中所说,在 for 循环之前移动数组初始化:

       var random_array = [];
      

      还要改变

      random_array[i] = random_index;
      

      random_array.push(random_index);
      // or
      random_array[random_array.length] = random_index;
      

      要获得您正在寻找的随机播放结果。

      【讨论】:

        【解决方案4】:

        如果您想为数组的每个元素执行代码,除非您需要执行某些需要 for 的操作,否则您可以使用 array.forEach() 而不是 for,非常确定。

        vocab_array_1.forEach(
            function (element, index, array) {
                var random_index = vocab_array_1[Math.floor(Math.random() * vocab_array_1.length)];
           random_array.push(random_index);
        });
        

        【讨论】:

          【解决方案5】:

          我的答案是针对那些来这里搜索类似于“循环在一次执行后停止”的人

          如果您的循环在一次执行后停止,则可能是您有嵌套循环,并且范围错误: 见例子

          functionA = async()=>{
            for (i = 0; i<count; i++) {
              ....
              ....
            }
          }
          
          
          functionB = async () =>{
            for (i=0;i<length; i++){
              result.push(await functionA());
            }
          }
          functionB();
          

          现在在函数 B 中,i 在两个函数中都具有全局作用域; 如果情况与您的情况相似,scope 正确,它应该可以工作。

          functionB = async () =>{
                for (var i=0;i<length; i++){    //    < ---------------- Note 'var'
                  result.push(await functionA());
                }
              }
          

          【讨论】: