1
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.

asked Dec 11, 2017 at 15:56

2 Answers 2

1

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.

answered Dec 11, 2017 at 16:06
Sign up to request clarification or add additional context in comments.

Comments

0

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

answered Dec 11, 2017 at 16:25

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.