Any way to simulate passing a number by reference, rather than a value, to a function?

I understand that this is not how primitive values ​​are passed, but what is the best way to do this? There are listeners who should watch the object o, so I need n and m to always be in the synchronization of the object o, but I also need the number property to increase to be variable, so that I can pass different depending on some coefficient to addOneTo.

var o = {a: [], b: [], n: 5, m: 6};
function push5To(arr){
  arr.push(5);
}
push5To(o.a);
o.a[0]; // 5
function addOneTo(num){
  num += 1;
}
addOneTo(o.n);
o.n; // 5 :(
+4
source share
1 answer

This is because javascript arrays are passed by reference. o.a- an array. o.nno, this is a prime number.

- o.n. :

function addOneTo(map,key){
  map[key] += 1;
}

addOneTo(o,'n');

, @Phrogz "box it", , . . :

var o = {a: [], b: [], n: {"value":5}, m: 6};

function addOneTo(key){
   key.value += 1;
}

EDIT. "Pass by reference". " ". , ( javascript ), . , . . - (, ) .

+4

All Articles