-3

I am starting to learn Javascript and I do not understand the following:

I need to execute the method "pay" in order to pay all the different persons; so, I need to complete the function "salary". The function receives an array object; all those objects "know" how to execute the method "pay". Also, I want to store the result in the array "result".

I did this but it seems it's not working:

function salary($persons) {
  $results= [];

  $persons->pay();

  return $results;
} 

What am I missing? What's wrong with my function?

  • Hey, So reading your question a few times I have the feeling you are trying to learn JavaScript by taking a rocket to the moon. Alright that's a little hyperbole but but it's important to remember to walk before running. Anyway perhaps taking a look at sites like w3schools.com/js and working through your questions one at a time until you have a solution be a good use of your time. – hoss Oct 09 '19 at 00:16
  • That looks like PHP rather than Javascript... – Robin Zigmond Oct 09 '19 at 00:22
  • @RobinZigmond How would you do that in PHP only? –  Oct 09 '19 at 00:38
  • Main recommendation I would have generally, is to always look at the compilation error provided, and give it into your question. It should give you at least a partial hint on what the problem is and where it lies. – Pac0 Oct 09 '19 at 03:28

1 Answers1

2

-> is not Javascript syntax.

To construct one array by performing an operation on each item of another array, use .map:

function salary(persons) {
  return persons.map(person => person.pay());
} 

function salary(persons) {
  return persons.map(person => person.pay());
}

console.log(salary([
  { pay: () => 5 },
  { pay: () => 10 }
]));

Since this isn't PHP, there's no need to prefix variables with $ either.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • Because since `persons` is an array (right?), it makes sense to call each individual item of the array a `person` object (from which you can then access the `.pay` property of that object). – CertainPerformance Oct 09 '19 at 00:23
  • Thank you for replying.. i got this question in my mind: Is not possible to use php inside a javascript function? –  Oct 09 '19 at 00:26
  • No. https://stackoverflow.com/questions/13840429/what-is-the-difference-between-client-side-and-server-side-programming – CertainPerformance Oct 09 '19 at 00:28
  • Dude, thank you very very much. Last question: how would you do to perform the same but using PHP? –  Oct 09 '19 at 00:32
  • I pretty much never use PHP, but maybe something like `array_map(function($person) { return $person->pay() }, $persons)`, no idea if that syntax is right though – CertainPerformance Oct 09 '19 at 00:35
  • Yeah, i dont know how to do that in php only :/ –  Oct 09 '19 at 01:06