Zakery Clarke
Zakery Clarke

Reputation: 55

Object Constructor with for loop doesnt work

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

This code is my attempt at creating a neural network. The problem is that when I run the code, it only creates the first object for each array instead of looping through all the objects it should create. For example, the test.layer array should contain three layer objects but it stops after the first one. Same with the layer.nodes and the nodes.weights. Thanks in advance for your help.

Upvotes: 1

Views: 165

Answers (2)

Herohtar
Herohtar

Reputation: 5613

You need to use var i = 0 in your for loops to make it create a new local variable.

When you use just i = 0 by itself in the for statement it expects i to already exist. When it doesn't, it creates it at the global level, the same as if you had written var i = 0 at the top level of your code. All of your subsequent for loops that reference i will use this new global i instead of having their own local i. Because of that, when your network constructor calls the first layer constructor, the global i will be set to 2 once it returns to the original function. Back in the network loop, it increments i by 1, making it 3, then checks the condition and exits without creating the other layers.

Upvotes: 1

Sanjucta
Sanjucta

Reputation: 127

In your for loops when declaring the loop variable i , use var

Upvotes: 0

Related Questions