JonesyH JonesyH - 4 months ago 9
CoffeeScript Question

Invoke each Function in array of Classes

If i had numerous

Person
Objects stored in an
array
, how would i invoke the same function for each object.

class Person
constructor: (_age) ->
@age = _age

addAge: (_num) ->
@age = @age + _num



_peeps = [new Person(5),new Person(9),new Person(50)]

_peeps.addAge(2)


Im looking for something better than multiple
for
loops or alike , as ideally there be would numerous
Person
Objects with even more methods.

Is there a workaround for this ?

Thanks, Have a good day!

Answer

You can try this:

result = _peeps.map (o) -> return o.addAge(2)

Or:

_peeps.forEach (o) -> o.addAge(2)

Demo: https://jsfiddle.net/iRbouh/7e0L1hpq/

Comments