简体   繁体   中英

Rewrite array from the function. Using argument reference

Can you please explain how to worship JavaScript gods and work around this one.

 var array = ['old']; function manageArray(targetArray) { targetArray = ['new']; } manageArray(array); alert(array); 

The reason for this is to create a pattern that will have filter logic and instead of declaring explicit methods for each array have one universal to rule over all.

Desired logic

var numbers = ['1', '2']
var words = ['room', 'car']
var color = ['red', 'blue']

function manageArray(targetArray, value) {
  targetArray = targetArray.filter(existingValue, () => {
    return existingValue != value
  })
}

manageArray(words, 'car');
alert(words);

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

 var array = ['old']; function manageArray(targetArray) { targetArray = ['new']; return targetArray } array = manageArray(array); alert(array); 

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.

var array = {v: ['old'] };

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

manageArray(array);

or

var array = ['old'];

function manageArray(targetArray) {
    return ['new'];
}

array = manageArray(array);

For further reading:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM