jQuery - 如果array.filter失败,显示消息?

时间:2012-09-17 13:17:08

标签: javascript jquery arrays array-filter

我正在创建一个jQuery控制台,我正在使用一个充满可用命令的数组来验证用户的输入 - 例如,如果他们输入help,如果help是在array.name中,然后继续下一段代码。

问题是当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时在阵列中的任何位置找不到命令名,是否有办法显示消息?

在此先感谢,如果我没有意义,并且对代码墙感到抱歉,我愿意接受其他方法的建议。

1 个答案:

答案 0 :(得分: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???");
});

放轻松。