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

0

2 Answers 2

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);
Sign up to request clarification or add additional context in comments.

Comments

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');

3 Comments

tnx for feeback.acullay it is a demo problem,i want to use common function to compact my my project.
How can i pass by reference?
You can't. maybe if you explained what you really want to achieve, with an example that makes more sense, we could help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.