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

146
Vistas
Una copia de una matriz cambia la matriz original incluso con el corte

Estoy tratando de crear una copia de una matriz para poder realizar cambios en la copia mientras sigo guardando la matriz original. Estoy usando la función de corte para copiar la matriz, pero por alguna razón todavía está cambiando ambas matrices. El código incrustado no se ejecutará porque estoy usando una fuente personalizada que no puedo importar

 let font; let num1; function preload() { font = loadFont("Pacifico-Regular.ttf") } function setup() { createCanvas(350, 350); num1 = new num("1", 350 / 2, 350 / 2, 200) num1.randomize(-5, 5) num1.show() } function draw() {} class num { constructor(text, centerX, centerY, fontSize) { this.text = text; this.centerX = centerX; this.centerY = centerY; this.fontSize = fontSize; this.oldArray = font.textToPoints(this.text, this.centerX, this.centerY, this.fontSize); this.newArray = this.oldArray.slice(); //Here is where I make a copy of the Array } //Randomizes old array randomize(min, max) { for (let i = 0; i < this.oldArray.length; i++) { this.oldArray[i].x = this.oldArray[i].x + random(min, max); this.oldArray[i].y = this.oldArray[i].y + random(min, max); } } //Draws new array show() { beginShape() for (let i = 0; i < this.newArray.length; i++) { vertex(this.newArray[i].x, this.newArray[i].y) } endShape(CLOSE) } //Moves new array move(x, y) { for (let i = 0; i < this.newArray.length; i++) { this.newArray[i].x = this.newArray[i].x + x; this.newArray[i].y = this.newArray[i].y + y; } } //Returns old array return() { this.newArray = this.oldArray.slice(); } }
 <script src="https://cdn.jsdelivr.net/npm/p5@1.4.0/lib/p5.js"></script>

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

No está cambiando la matriz, está mutando los objetos dentro de la matriz. No quieres eso.

 const myObj = { x:1, y:1 }; const myArray = [myObj]; const myNewArray = [...myArray]; myNewArray[0].x = 2; console.log(myArray[0].x); // 2!!!!!

Si está cambiando un objeto dentro de la matriz y no desea que mute, haga esto:

 const myObj = { x:1, y:1 }; const myArray = [myObj]; // helper function that will perform a mutation at a given position // and ignore all other positions const mutateObjectAtPosition = (pos,mutation) => [...myArray].map((o,i) => i === pos ? mutation(o) : o) // at position 0, return a **new object** with x set to 2 const myNewArray = mutateObjectAtPosition(0,(o) => ({...o,x:2})); console.log(myNewArray !== myArray); // true, different references console.log(myNewArray[0].x); // 2 console.log(myArray[0].x); // 1
about 4 years ago · Juan Pablo Isaza Denunciar

0

La nueva forma de copiar una matriz es la siguiente:

 const cloneSheepsES6 = [...sheeps];

Pero creo que su problema podría ser con la línea:

 return() { this.newArray = this.oldArray.slice(); }

Donde devuelve la nueva matriz pero la configura para que sea una copia nuevamente de la anterior. Entonces, creo que simplemente devolviendo el newArray debería haber solucionado su problema.

about 4 years ago · Juan Pablo Isaza Denunciar
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