Javascript 具有for循环的对象构造函数不起作用 var测试=新网络([2,3,1]); test.reset(); console.log(test.layers); 功能网络(args){ 这个。层=[]; 此.numberoflayers=args.length; 这是重置= 函数(){ for(i=0;i

Javascript 具有for循环的对象构造函数不起作用 var测试=新网络([2,3,1]); test.reset(); console.log(test.layers); 功能网络(args){ 这个。层=[]; 此.numberoflayers=args.length; 这是重置= 函数(){ for(i=0;i,javascript,object,Javascript,Object,您需要在for循环中使用var i=0,使其创建一个新的局部变量。 当您在for语句中单独使用i=0时,它期望i已经存在。如果它不存在,它将在全局级别创建它,就像您在代码的顶层编写var i=0一样。引用i的所有后续for循环都将使用这个新的全局i而不是拥有自己的本地i。因此,当您的网络构造函数调用第一层构造函数时,全局i将在返回原始函数后设置为2。回到网络循环中,它将i增加1,使其为3,然后检查条件并退出,而不创建其他层。在for循环中,当声明循环变量i时,使用var var test=new

您需要在for循环中使用
var i=0
,使其创建一个新的局部变量。


当您在for语句中单独使用
i=0
时,它期望
i
已经存在。如果它不存在,它将在全局级别创建它,就像您在代码的顶层编写
var i=0
一样。引用
i
的所有后续for循环都将使用这个新的全局
i
而不是拥有自己的本地
i
。因此,当您的网络构造函数调用第一层构造函数时,全局
i
将在返回原始函数后设置为2。回到网络循环中,它将
i
增加1,使其为3,然后检查条件并退出,而不创建其他层。

在for循环中,当声明循环变量i时,使用var

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