我的代码无限编码并使页面崩溃

My code code infinitely and crashes the page

这是我的代码:

// Population
var Gene = function(text){
    if(text){
        this.text = text;
    }
};

Gene.fitness = 0;
Gene.generation = 0;

var word = new Gene('Hello');

// This is where it crashes!!
// Make elements
var genArr = [];
var population = 20;
var mutation = 0;
for(var i = 0; i < population; i++){
   var gene = "";
    var abc = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    for (var j = 0; i < word.text.length; j++) {
        var element = abc.charAt(Math.floor(Math.random() * abc.length));
        gene += element;
    }
    genArr.push(gene);
}

// Divide them - fitness
// 1/20 - 0.05% each
var fitElements = [];
for (var i = 0; i < genArr.length; i++) {
    var score = 0;
    var curWord = Array.from(genArr[i]);
    for (var j = 0; j < word.text.length; j++) {
        if(genArr[j].substr(j, 1) == word.text.substr(j, 1)){
            score += 1;
        }
    }
    if(score > 0){
        fitElements.push([genArr[i], (score * (1 / population)) ** 2]);
    }
}

for (var i = 0; i < fitElements.length; i++) {
    console.log('Element: ' + fitElements[i][0] + ', Score: ' + fitElements[i][1]);
}

我的问题是它使页面崩溃但没有给出错误。我的想法是在 fitElements 数组中创建一个简单的单词寄存器,但我看不出我错过了什么? 提前致谢。

在您的代码中,带有变量 j 结束条件的嵌套 for 循环依赖于 i。 搭一条线:

//             VVVV it relies on i instead of j
for (var j = 0; i < word.text.length; j++) {
    var element = abc.charAt(Math.floor(Math.random() * abc.length));
    gene += element;
}

新代码看起来像

for (var j = 0; j < word.text.length; j++) 
    var element = abc.charAt(Math.floor(Math.random() * abc.length));
    gene += element;
}

整个样本的唯一区别是 i 更改为 j。干杯!