0

I have two list

men=['x','y','z']
women=['a','b','c'];

and two vabriable to show in html

selectedMan;
selectedWoman;

i want to create a common select method

select(index,source,destination){
  destination=source[index];
}

function call

this.select(2,this.men,this.selectedMan);
this.select(1,this.women,this.selectedWoman)

html

<p>Welcome to team {{selectedMan}}</p>
<p>Welcome to team {{selectedWoman}}</p>

but in html only show welcome to team

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567

2 Answers2

2

Arguments are passed by value, not by reference. All your function does is to change the value of the local variable destination. So it actually does nothing.

Frankly, I don't see the point. Even if it worked,

this.select(1,this.women,this.selectedWoman) 

is longer, and less clear than

this.selectedWoman = this.women[1];

If you really wanted such a function, you would need, for example

select(index: number, array: Array<string>, callback: (s: string) => void) {
  callback(array[index]);
}

and use it this way:

this.select(1, this.men, s => this.selectedMan = s); 

Or (but this is less safe, and doesn't allow for minification):

select(index: number, array: Array<string>, property: string) {
  this[property] = array[index]);
}

and call it like this:

this.select(1, this.men, 'selectedMan');
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
2

If you want to create a common function do it the right way.Learn the difference between pass by value and pass by reference. What's the difference between passing by reference vs. passing by value?

Solution

Method definition

select(index,source){
 return source[index];
}

method call

 this.selectedMan=this.select(2,this.men)
 this.selectedWoman=this.select(1,this.women);
Vikas
  • 11,859
  • 7
  • 45
  • 69