I’m making a jQuery console and I’m using an array filled with the available commands to validate the user’s input–so, for example, if they enter help, if help is in array.name, then continue to the next bit of code.
The problem is that I want to display a message such as “that command does not exist” when the filter fails entirely, as in help is not in the array at all. Here is my code so far:
var commands = [
{ 'name': 'help',
'desc': 'display information about all available commands or a singular command',
'args': 'command-name' },
{ 'name': 'info',
'desc': 'display information about this console and its purpose' },
{ 'name': 'authinfo',
'desc': 'display information about me, the creator' },
{ 'name': 'clear',
'desc': 'clear the console' },
{ 'name': 'opensite',
'desc': 'open a website',
'args': 'url' },
{ 'name': 'calc',
'desc': 'calculate math equations',
'args': 'math-equation' },
{ 'name': 'instr',
'desc': 'instructions for using the console' }
];
function detect(cmd) { // function takes the value of an <input> on the page
var cmd = cmd.toLowerCase(); // just in case they typed the command in caps (I'm lazy)
commands.filter(function(command) {
if(command.name == cmd) {
switch(cmd) {
// do stuff
}
}
else {
alert("That command was not found."); // this fires every time command.name != cmd
}
}
}
I have a jsFiddle with (almost) all the code if need be.
http://jsfiddle.net/abluescarab/dga9D/
The else statement fires every time the command name isn’t found–which is a lot, since it’s looping through the array.
Is there a way to display a message if the command name is not found anywhere in the array while using filter?
Thanks in advance, apologies if I didn’t make sense and for the wall of code, and I am open to suggestions of alternative ways to do this.
and not switch is try filter method function:
take it easy.