la operación de "=" en javascript
Frecuentes
Visto 77 veces
3
considere el siguiente código
var pub_json_general = {"holis":["12/10/2013","12/25/2013","12/26/2013"]};
var holiday = {"holis":["12/02/2013"]};
var pub_json = pub_json_general;
pub_json.holis = $.merge(pub_json.holis,holiday.holis);
After merge, the length of pub_json.holis becomes 4, that's correct. However, when I use firefox debugger, I found that pub_json_general.holis would also be changed, that means pub_json_general and pub_json would always be the same.
So is that "=" operation in javascript is not copying the right-hand side and create the left-hand side to store it but just create the left-hand side which will share the the same memory space with right-hand side?
3 Respuestas
3
Sí, you have explained everything correctly by yourself :)
Para los tipos de referencia, el igualdad asignación operador assigns reference to the object, it does not clone the object. Therefore when you change one, the other changes too.
respondido 27 nov., 13:07
1
So is that "=" operation in javascript is not copying the right-hand side and create the left-hand side to store it but just create the left-hand side which will share the the same memory space with right-hand side?
This is a very confusing question. If you are trying to understand what is happening in the last statement, here it is:
La expresion
$.merge(pub_json.holis,holiday.holis)
is evaluated. As a result, the contents ofholiday.holis
are appended to the array residing atpub_json.holis
(which is the same array as the one referred to bypub_json_general.holis
).The result of the expression is the newly altered
pub_json.holis
formación.The result from 1,
pub_json.holis
, is assigned topub_json.holis
, which understandably does nothing, and is a non-op.
Respondido el 20 de junio de 20 a las 10:06
1
You may want to take a look at this question ¿Cuál es la forma más eficiente de clonar en profundidad un objeto en JavaScript? para resolver tu problema
contestado el 23 de mayo de 17 a las 13:05
No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas javascript or haz tu propia pregunta.
Everything in JS is pass por valor. In case of objects, the value happens to be a reference to the object. That is not the same as pasar por referencia! - Félix Kling
You're right, my bad. It was an unfortunate mental shortcut. I've deleted the misleading sentence - Adassko