2
var action = ['function1','function2' etc ]
var obj = new objectcreate ();

for (functionname in action){
    obj+'.'+action[variablename]+'()';      
}

the functions are already generated I just wanna go through an array and execute all the functions it on the object i created thanks for your help

1
  • for (functionname in action) doesn't do what you think; functionname will be properties of the Array, which may not be in numerical order and can return other properties depending on browser. Never use for...in on Array. Instead use the plain old C-style loop for(var i= 0; i<array.length; i++). Commented Jan 5, 2010 at 0:10

3 Answers 3

3

obj[action[functionname]](); will do the trick.

Sign up to request clarification or add additional context in comments.

2 Comments

what if you didn't have an array of function names? Could this still be done?
@PrimeByDesign I don't get you. If you have no function names available, the best you could do is enumerate all the fields of the objects and invoke those which are functions.
3

You should be able to do this.

obj[action[functionName]]();

Comments

1

None of the answers above worked for me.

Noting that we are 10.5 years on from the original post the chances are JS have evolved.

My solution is:

window[action[functionName]]();

A solution tailored to the original question is as follows:

var action = ['test1','test2'];


function test1(){
   alert("test 1 running");
}

function test2(){
    alert("test 2 running");
}

for (var i=0; i<action.length; i++){
    window[action[i]]();
}

Expected output is an alert box saying "test 1 running" followed by another alert box saying "test 2 running".

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.