简体   繁体   中英

Uncaught TypeError: Cannot read property 'Array' of undefined error in JS

I'm making a very simple AI it's my first one and I keep getting an error when the function to generate random numbers for the weight array. This code is just to test if it's working properly Error log:

Uncaught TypeError: Cannot read property 'weights' of undefined Line: 9 var weight = new Array[];

Here's the entire code because apparently I have to post all of it and not the minimum like suggested by stack overflow:

 class preseptron { constructor(weights, inputs) { this.weights = new Array(); this.inputs = new Array(inputs); this.output; function preseptron() { for (var i = 0; i < 15;) { this.weights[i].push(Math.random(-1, 1)); i++ } } function sum() { var sum = 0 for (var j = 0; j < this.weights.length;) { sum += inputs[j] * weights[j]; } var output = Math.sin(sum) if (output > 0) { output = 1; } if (output < 0) { output = -1; return output; } } preseptron() sum() document.write(output); } } var test = new preseptron(15, 15);

You're trying to get weight from within different function scopes instead of the base class scope. Simply replacing them to use arrow functions which don't redefine this or setting weight to a variable fixes this problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM