Can not read property of undefined?

I don’t understand why can’t the value in the array be pushed, my maths seems right. The program chooses groups of 9 pixels and checks the contrast, and if it’s higher than 100 it draws a circle in that area. How do I fix the error?

Again you’re swapping the order of row & column indices! :scream:

For best performance stick w/ the row & column order both at creating & accessing your 2D arrays. :running_man:

In this case I think that incredibly vague Javascript error message might have been triggered by attempting to access the arrays with out of bounds indexes.

I don’t know how to use Javascript OOP stuff like “Class” and “constructor” so this is tweaked a little. Also Javascript does some weird stuff with scope and trying to reference stuff.

I think I got it to work though (at least almost):

let cur;

let cols = 800;
let rows = 744;

let grid = new Array(cols);

function preload(){
	cur = loadImage('gamer.jpg');
}

function setup() {
	cur.resize(400, 372);
	createCanvas(800, 744);
	background(255);
	
	for(x = 0; x < cols; x = x + 1){
    grid[x] = new Array(rows);
  }

	cur.loadPixels();
	for(y = 0; y < cur.height; y++){
		for(x = 0; x < cur.width; x++){
			let index = (x + y * cur.width) * 4;
			
			let r = cur.pixels[index];
			let g = cur.pixels[index + 1];
			let b = cur.pixels[index + 2];

			let bright = (r + g + b) / 3;
			
			grid[x][y] = new Pxl(x, y, bright);
		}
	}	
}

function draw() {
	var ind = 1;
	var total = cur.width * (cur.height - 3);
	for(y = 0; y < cur.height-3; y++){
		for(x = 0; x < cur.width; x++){
			if((x + 1) % 3 == 0 && (y + 1) % 3 == 0){
				grid[x][y].findFriends(grid);
			}
			ind++;
			if(ind % 100 == 0) print(ind / total);
		}
	}
	noLoop();
}

var Pxl = function(x, y, b) {
	this.x = x;
	this.y = y;
	this.b = b;

	this.brights = [];
}

Pxl.prototype = {
	findFriends: function(grid) {
		var brights = this.brights;

		var left = this.x - 1;
		if(left < 0) left += cur.width;
		
		var right = this.x + 1;
		if(right > cur.width) right %= cur.width;
		
		var up = this.y - 1;
		if(up < 0) up += cur.height;
		
		var down = this.y + 1;
		if(down > cur.height) down %= cur.height;

		brights.push(grid[left][up].b);
		brights.push(grid[left][down].b);
		brights.push(grid[left][this.y].b);
		brights.push(grid[this.x][up].b);
		brights.push(grid[this.x][down].b);
		brights.push(grid[this.x][this.y].b);
		brights.push(grid[right][up].b);
		brights.push(grid[right][down].b);
		brights.push(grid[right][this.y].b);

		this.max = max(this.brights);
		this.min = min(this.brights);
		this.con = this.max - this.min;
		
		if(this.con > 100){
			ellipse(this.x * 2, this.y * 2, 1);
		}
	}
}