Skip to content Skip to sidebar Skip to footer

Rewrite Array From The Function. Using Argument Reference

Can you please explain how to worship JavaScript gods and work around this one. The reason for this is to create a pattern that will have filter logic and instead of declaring exp

Solution 1:

From what I understand, you want to pass your variable by reference. It is sad that Javascript pass array as value. There are a few ugly workaround.

vararray = {v: ['old'] };

functionmanageArray(targetArray) {
  targetArray.v = ['new'];
}

manageArray(array);

or

vararray = ['old'];

functionmanageArray(targetArray) {
    return ['new'];
}

array = manageArray(array);

For further reading:

Solution 2:

You'll be able to access the array if you have your function return it:

var array = ['old'];
    
functionmanageArray(targetArray) {
  targetArray = ['new'];
  return targetArray
}

array = manageArray(array);
alert(array);

Post a Comment for "Rewrite Array From The Function. Using Argument Reference"