-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();
4
  • 1
    myObjects.forEach(obj => obj.doThis()) Commented May 23, 2017 at 22:35
  • Not sure gather Question. Is there javascript not included at OP? Commented May 23, 2017 at 22:35
  • 2
    "I have the following objects in an array" — Those are strings Commented May 23, 2017 at 22:39
  • @Quentin Well I have objects with the names in an array. Commented May 23, 2017 at 22:59

1 Answer 1

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

4 Comments

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]].
Yeah my bad, wasn't immediately clear.
You're confusing this with an EnvironmentRecord, which is part of an execution context. A function's this is a parameter of an EnvironmentRecord and has nothing to do with scope or variables.
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?).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.