Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

203
Views
¿Javascript que reasigna el valor de la matriz ya no hace referencia?

No estoy seguro de cómo explicar la pregunta. Sin embargo, aquí hay un código muy simple para demostrarlo.

Esperaría que testValue y testValue2 fueran [20, 21, 22], ya que se pasan por referencia y no por valor, según tengo entendido, y según parece, ya que se actualizan con .push( ) método.

¿Alguien sabe lo que está pasando aquí? ¿Por qué tanto testValue como testValue2 parecen comenzar a pasar por valor después de que reasignamos la matriz original?

 let testArray = [1, [10, 11, 12], 3, 4, 5]; let testValue = testArray; testArray.push(13); testArray = [20, 21, 22]; console.log(testArray); console.log(testValue); //Different attempt let testArray2 = [1, [10, 11, 12], 3, 4, 5]; let testValue2 = testArray2[1]; testArray2.push(13); testArray2[1] = [20, 21, 22]; console.log(testArray2); console.log(testValue2);

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

problema: memoria de ubicación.

crea una nueva variable testValue con testArray , estas 2 variables tienen la misma memoria de ubicación, luego usa .push() empujará el nuevo valor a la memoria de ubicación de la variable, no depende de la matriz que la use.

si no quieres que tengan la misma memoria de ubicación. utilizar este:

 // Array.from let testArray = [1, [10, 11, 12], 3, 4, 5]; let testValue = Array.from(testArray); // spread operator let testArray = [1, [10, 11, 12], 3, 4, 5]; let testValue = [...testArray];

para más detalles revisa este artículo:

  1. https://backbencher.dev/articles/javascript-variables
  2. https://medium.com/@ethannam/javascripts-memory-modelo-7c972cd2c239
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!