2012-09-17 66 views
1

我正在制作一个jQuery控制台,我正在使用一个填充了可用命令的数组来验证用户的输入 - 例如,如果它们输入help,如果helparray.name中,则继续下一位的代码。jQuery - 如果array.filter失败,显示消息?

问题是,当filter完全失败时,我想显示诸如“该命令不存在”之类的消息,因为help根本不在数组中。这是我到目前为止的代码:

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 
     } 
    } 
} 

我有(几乎)所有的代码的jsfiddle如果需要的话。

http://jsfiddle.net/abluescarab/dga9D/

else语句每次触发命令名称没有找到时间 - 这是很多,因为它是循环遍历数组。

如果在使用filter时未在数组中的任何位置找到命令名称,是否有方法显示消息?

在此先感谢,如果我没有理解和代码墙,并且我愿意接受其他替代方法的建议,请致歉。

+0

你可以使用布尔值来标记它是否被找到?所以在你的else语句中,而不是像“notFound = true;”这样的提示符,那么当你的循环结束时,只需检查(notFound){//做些什么},这样你的错误只会触发一次。 – zgood

+0

@zgood感谢您的建议。我会立即尝试并回复你。 – Abluescarab

+0

@zgood无论值是否被找到,数组仍然循环到最后。我使用“返回”来试图阻止循环,但它不起作用。 – Abluescarab

回答

1
function get_command(command_name) { 

    var results = {}; 
    for (var key in commands) (function(name, desc, command) { 

     if (name == command_name) (function() { 

      results = command; 
     }()); 

    }(commands[key]["name"], commands[key]["desc"], commands[key])); 

    return (results); 
}; 

get_command("help"); 

,而不是切换为尝试过滤方法功能:

commands.filter = (function(command, success_callback, fail_callback) { 

    if (get_command(command)["name"]) (function() { 

     success_callback(); 
    }()); 

    else (function() { 


     fail_callback(); 
    }()); 
}); 


commands.filter("help", function() { 

    console.log("enter help command source :)"); 
}, function() { 

    console.log("hey help command???"); 
}); 

处之泰然。

+0

谢谢!这很好!我无法破译它,但效果很好。我只是检查get_command()['name']是否返回undefined? – Abluescarab

+1

使用commands.filter(command,success_callback,fail_callback)好吗? –

+0

是的!再次感谢你!这一切都很好! – Abluescarab

相关问题