我正在制作一个jQuery控制台,我正在使用一个填充了可用命令的数组来验证用户的输入 - 例如,如果它们输入help
,如果help
在array.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
时未在数组中的任何位置找到命令名称,是否有方法显示消息?
在此先感谢,如果我没有理解和代码墙,并且我愿意接受其他替代方法的建议,请致歉。
你可以使用布尔值来标记它是否被找到?所以在你的else语句中,而不是像“notFound = true;”这样的提示符,那么当你的循环结束时,只需检查(notFound){//做些什么},这样你的错误只会触发一次。 – zgood
@zgood感谢您的建议。我会立即尝试并回复你。 – Abluescarab
@zgood无论值是否被找到,数组仍然循环到最后。我使用“返回”来试图阻止循环,但它不起作用。 – Abluescarab