-1

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();
KingKongFrog
  • 13,946
  • 21
  • 75
  • 124

1 Answers1

0

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())
varbrad
  • 474
  • 3
  • 11
  • 1
    I think you missed the point of the question. The OP wants to use the strings as variable names similar to accessing object properties using square bracket notation, something like `variableObj[myObjects[0]]`. – RobG May 23 '17 at 22:58
  • Yeah my bad, wasn't immediately clear. – varbrad May 23 '17 at 23:04
  • You're confusing *this* with an [*EnvironmentRecord*](http://www.ecma-international.org/ecma-262/7.0/index.html#sec-lexical-environments), which is part of an [*execution context*](http://www.ecma-international.org/ecma-262/7.0/index.html#sec-execution-contexts). A function's *this* is a parameter of an *EnvironmentRecord* and has nothing to do with scope or variables. – RobG May 23 '17 at 23:12
  • That's why I added the "should work" part, there was no way of knowing in what situation this code is running (a function? globally? lambda/arrow func?). – varbrad May 23 '17 at 23:45