Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

114
Vistas
Nested functions not affecting objects in bidimensional array declared within global scope

I have a bidimensional array filled with Cell objects.

How can I do to make addToGrid(asset); (and nested functions) use the context of each Cell to set cells so that I can use it in draw method ?

class Cell {
  constructor(value) {
     this.value = value;
  }
  
  makeAlive = () => {
    this.value |= (1 << 0)
  }

  incrementNeighbours = (num) => {
    this.value += 2;
  }
}

// Main
let cols;
let rows;
let cells;
let resolution = 2;
let infos = {};

s.setup = async () => {
  cols = 256;
  rows = 256;
  s.createCanvas(cols * resolution, rows * resolution);
  s.frameRate(60);

  cells = [...Array(cols)].map(x => Array(rows).fill(new Cell(0)));
  const loader = new AssetLoader();
  const asset= await loader.loadAsync('type', 'name');

  addToGrid(asset);
}

s.draw = () => {
    .
    .
    .
    // cells is not affected by addToGrid

}

const addToGrid = (asset) => {
  for (let i = 0; i < asset.length; i++) {
    .
    .
    .
    addStrToGrid(col, row, asset[i]);
  }
}

const addStrToGrid = (col, row, str) => {
  for (const c of str) {
      becomeAlive(col, row);
  }
}

const becomeAlive = (x, y) => {
  cells[x - 1][y - 1].incrementNeighbours();
  cells[x - 1][y].incrementNeighbours();
  cells[x - 1][y + 1].incrementNeighbours();
  cells[x][y - 1].incrementNeighbours();
  cells[x][y].makeAlive();
  cells[x][y + 1].incrementNeighbours();
  cells[x + 1][y - 1].incrementNeighbours();
  cells[x + 1][y].incrementNeighbours();
  cells[x + 1][y + 1].incrementNeighbours();
}

s.setup & s.draw are from the library p5.js which are triggered respectively !

about 4 years ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda