开发者

javascript / jQuery - match a function from array of function

开发者 https://www.devze.com 2023-03-01 12:59 出处:网络
so I have a array of functions like this one: var functions = [ func1 = function(){ ... }, func2 = function(){ ... 开发者_高级运维},

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)?


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.


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);


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

精彩评论

暂无评论...
验证码 换一张
取 消