为什么这个简单的.js在一次迭代后循环停止

Why is this simple .js for loop stopping after one iteration?

本文关键字:迭代 一次 循环 简单 js 为什么      更新时间:2023-09-26

我正在尝试制作一个简单的小.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);

移动此行

var random_array = [];

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

你的代码应该是这样的

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

循环之外初始化数组。

如前面的答案中所述,在for循环之前移动数组初始化:

 var random_array = [];

但也要改变

random_array[i] = random_index;

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

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

很确定你可以使用 array.forEach() 而不是 for ,如果你想为数组的每个元素执行代码,除非你需要做一些需要 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);
});

我的答案适用于来这里搜索类似于"一次执行后循环停止"的人

如果您的循环在

一次执行后停止,则可能是您有嵌套循环,并且作用域错误:查看示例

functionA = async()=>{
  for (i = 0; i<count; i++) {
    ....
    ....
  }
}

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

现在在函数 B 中,i在这两个函数中都具有全局范围;如果情况与您的情况相似,请正确确定其范围,它应该可以工作。

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