I want to call different functions depending on the input I find. If the input matches one of the keys, I want to call the corresponding function - with some parameters:
var commands = {
'key1': someFunction,
'key2': otherFunction
};
The keys are strings and to make it easier I created the command_keys variable:
var command_keys = Object.keys(commands);
I define the two functions further down:
function someFunction(param) {
// do sth.
};
function otherFunction(param) {
// do sth. else
};
Then I have a condition checking for the key and calling one of the functions depending on what key I found:
if (command_keys.indexOf(some_string) > -1) {
index = command_keys.indexOf(some_string);
commands[index](some_param);
}
However, I get an error:
Uncaught TypeError: commands[index] is not a function(anonymous function)
Thank you for your ideas.
asked Aug 8, 2015 at 21:24
Randomtheories
1,29019 silver badges23 bronze badges
1 Answer 1
I don't think you need command_keys at all. commands alone will suffice for what you describe here.
var commands = {
'key1': someFunction,
'key2': otherFunction
};
var command = commands[some_string];
if (typeof command === 'function') {
command(some_param);
}
answered Aug 8, 2015 at 21:49
Noah Freitas
17.5k11 gold badges53 silver badges67 bronze badges
Sign up to request clarification or add additional context in comments.
4 Comments
zerkms
What if
command_keys is some sort of filter of applicable commands in a given context? Like, we have an edit command but we cannot perform it when something is in a read-only mode.Noah Freitas
Well then, you could keep it around and add another condition to the if
typeof command === 'function' && command_keys.indexOf(some_string) !== -1. command_keys is still not useful for retrieving the actual command from commands based on some_string, though.zerkms
That's right. My point was that you cannot put the "I don't think you need command_keys at all" statement unless some more details provided. PS: oh, I just noticed
var command_keys = Object.keys(commands);, so seems right it's indeed redundant.Randomtheories
@NoahFreitas. Thanks for pointing this out. I solved the problem thanks to zerkms as I used the index instead of the key.
lang-js
some_array? It would be better if you show us the full script.command_keysis an array, thenindexis an integer andcommandsdoes not have integer keys.