I have an array that has a bunch of function names. I am not storing the function in an object.
for (i = 0; i < view_functions.length; i++) {
view_functions[i]();
}
This doesn't work, any ideas?
Thanks.
I have an array that has a bunch of function names. I am not storing the function in an object.
for (i = 0; i < view_functions.length; i++) {
view_functions[i]();
}
This doesn't work, any ideas?
Thanks.
The code you posted works, so perhaps the code that defines the functions isn't quite right. Here is a fully working example.
function yep() {
alert('Yep');
}
function again() {
alert('Again');
}
var view_functions = [
yep,
again
];
for (var i = 0; i < view_functions.length; i++) {
view_functions[i]();
}
If you wanted to get a bit of design help in your code, you could introduce a factory. This has the added benefit of making unknown function names explicit.
function yep() {
alert('Yep');
}
function again() {
alert('Again');
}
function functionFactory(name) {
switch (name) {
case 'yep':
return yep;
case 'again':
return again;
default:
throw `${name} not a known function in functionFactory`;
}
}
var view_functions = [
'yep',
'again'
];
for (var i = 0; i < view_functions.length; i++) {
var func = functionFactory(view_functions[i]);
func();
}
If you only have string names, I recommend not using string names... but you could go full-evil and use eval
...
function yep() {
alert('Yep');
}
function again() {
alert('Again');
}
var view_functions = [
'yep',
'again'
];
for (var i = 0; i < view_functions.length; i++) {
var n = view_functions[i] + '()';
eval(n);
}
But why not store the actual functions in the array instead...