Javascript 当我尝试使用.push时,在一个循环中,它似乎比间隔数早开始一个阶段,这似乎会导致溢出?
考虑这一功能:Javascript 当我尝试使用.push时,在一个循环中,它似乎比间隔数早开始一个阶段,这似乎会导致溢出?,javascript,jquery,Javascript,Jquery,考虑这一功能: function generation(input_text, characters, target_text, mutation_rate, amount_offspring) { var generationObject = [{string:"", score: 0}]; var evolved_string = ""; var best_offspring = {string:"", score: 0}; for(var i = 0; i <= amount_of
function generation(input_text, characters, target_text, mutation_rate, amount_offspring) {
var generationObject = [{string:"", score: 0}];
var evolved_string = "";
var best_offspring = {string:"", score: 0};
for(var i = 0; i <= amount_offspring; i++) {
evolved_string = evolve(input_text, characters, mutation_rate)
console.log("E= " + evolved_string);
generationObject.push({
string: evolved_string,
score: score(target_text, evolved_string)
});
console.log(generationObject[i]);
// if there are more then 2 elements in the object array.
Check if the current offspring has a higher score then the previous one.
If it does, its the best offspring
if (generationObject.length > 1) {
if (generationObject[i].score > best_offspring.score) {
best_offspring.string = generationObject[i].string;
best_offspring.score = generationObject[i].score;
}
}
// if there only is one offspring. Its the best, by defult.
else {
best_offspring.string = generationObject[i].string;
best_offspring.score = generationObject[i].score;
}
// increment generations
generations++;
return best_offspring.string;
}
但是在这里您可以看到
functions.js:18对象{string:,score:0}
在第一次运行时是这样的。为什么?使用单个对象初始化数组:
var generationObject = [{string:"", score: 0}]; //use var generationObject = []; instead
您的溢出错误来自此处:
i <= amount_offspring; //should be i < amount_offspring, since you start at 0
i使用单个对象初始化数组:
var generationObject = [{string:"", score: 0}]; //use var generationObject = []; instead
您的溢出错误来自此处:
i <= amount_offspring; //should be i < amount_offspring, since you start at 0
i您正在初始化数组,使其以一个对象开始。@Pointy Ok!我如何进行初始化,使其为空<代码>变量生成对象=[{string:,score:}]代码>像这样?不,像这样:var generationObject=[]代码>您正在初始化数组,使其以一个对象开始。@Pointy Ok!我如何进行初始化,使其为空<代码>变量生成对象=[{string:,score:}]代码>像这样?不,像这样:var generationObject=[]代码>是!这就成功了,谢谢!!我不知道你可以像那样初始化和对象数组。是的!这就成功了,谢谢!!我不知道你可以像那样初始化和对象数组。