I have the following objects in an array that I would like to loop through that have the same methods.
var myObjects = ['a','b','c'];
How do I loop through this array and call the same method?
a.doThis();
b.doThis();
c.doThis();
I have the following objects in an array that I would like to loop through that have the same methods.
var myObjects = ['a','b','c'];
How do I loop through this array and call the same method?
a.doThis();
b.doThis();
c.doThis();
You can use an Array.forEach(...)
loop to achieve this. It will loop through every object within the array and execute the given function.
var myObjects = ['a', 'b', 'c']
myObjects.forEach(o => o.doThis())
Array.prototype documentation (MDN)
EDIT: As Rob points out, if you are attempting to access actual objects called a
, b
and c
in some context (assuming this
context), you can do the following. It will depend on the context of where these objects are actually located. this
should work as long as myObjects
and your actual objects are defined within the same scope/context.
var myObjects = ['a', 'b', 'c']
myObjects.forEach(o => this[o].doThis())