0

so I have a array of functions like this one:

var functions = [
   func1 = function(){ ... },
   func2 = function(){ ... },
   func3 = function(){ ... }
] ;

If I call a function like functions[func1]() it works, but if I call it like functions['func1']() it doesn't.

What's the difference?

And how can I call a function using the 2nd method (match the function name with a string)?

3 Answers 3

4

It needs to be an object containing keys:

var functions = {
   func1: function(){ ... },
   func2: function(){ ... },
   func3: function(){ ... }
};

This will allow functions['func1']() to work.

I don't know how your functions[func1]() ever worked, though.

Your original code would have (inadvertently) created global variables (func1, etc) but those wouldn't have been valid indices into the functions array.

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

4 Comments

can I still use array like indexes on it? like functions[5] or functions[functions.length] etc?
Only if you also do something like: functions[0] = functions.func1 for each element. NB: array offsets start at zero.
but there are too many, I don't want to make the code so big :( Is there any way I could randomly pick a function from that object? (this is why I asked about the indexes)
Sure, pick a random number as an offset into the array returned by Object.getOwnPropertyNames(functions)
4

If you want to call a random function, try something like this (demo):

var functions = [
   [ function(el){ el.html('function 1'); } ],
   [ function(el){ el.html('function 2'); } ],
   [ function(el){ el.html('function 3'); } ]
],

    random = Math.round(Math.random() * functions.length),
    output = $('#display');

functions[random][0](output);

2 Comments

Why are you nesting all the functions in arrays?
@js1568: Because in the follow up comments, Alex asked if it was possible to pick a function using a random index.
1
var functions = {   
                func1: function(){ ... },   
                func2: function(){ ... },   
                func3: function(){ ... }
};

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.