var test=new network([2,3,1]);
test.reset();
console.log(test.layers);
function network(args){
this.layers=[];
this.numberoflayers=args.length;
this.reset=
function(){
for(i=0;i<this.numberoflayers;i++){
this.layers.push(new layer(args[i],args[i+1]));
this.layers[i].reset();
}
}
}
function layer(num,numlayer){
this.nodes=[];
this.reset=
function(){
for(i=0;i<num;i++){
this.nodes.push(new node(numlayer));
this.nodes[i].reset();
}
}
}
function node(num){
this.weights=[];
this.reset=
function(){
for(i=0;i<num;i++){
this.weights.push(0);
}
}
}
这段代码是我尝试创建一个神经网络。问题是当我运行代码时,它只为每个数组创建第一个对象,而不是遍历它应该创建的所有对象。例如,test.layer 数组应该包含三个图层对象,但它在第一个图层之后停止。与 layer.nodes 和 nodes.weights 相同。 预先感谢您的帮助。
最佳答案
您需要在 for 循环中使用 var i = 0
来创建一个新的局部变量。
当您在 for 语句中单独使用 i = 0
时,它期望 i
已经存在。如果没有,它会在全局级别创建它,就像您在代码的顶层编写 var i = 0
一样。所有后续引用 i
的 for 循环都将使用这个新的全局 i
而不是拥有自己的本地 i
。因此,当您的网络构造函数调用第一层构造函数时,一旦返回原始函数,全局 i
将被设置为 2。回到网络循环,它将 i
递增 1,使其成为 3,然后检查条件并退出而不创建其他层。
关于javascript - 带有 for 循环的对象构造函数不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47756658/