jQuery 콘솔을 만들고 사용자의 입력을 확인하기 위해 사용 가능한 명령으로 채워진 배열을 사용하고 있습니다. 예를 들어 help
을 입력하면 help
이 array.name
인 경우 다음 비트로 계속 진행합니다. 코드jQuery - array.filter가 실패하면 메시지를 표시 하시겠습니까?
help
이 배열에 전혀 없기 때문에 filter
이 완전히 실패 할 때 "해당 명령이 존재하지 않습니다."와 같은 메시지를 표시하려고합니다. 필요하다면
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
을 사용하는 동안 명령 이름을 배열의 어느 곳에서도 찾을 수없는 경우 메시지를 표시하는 방법이 있습니까?
미리 감사드립니다. 코드 벽에 적합하지 않은 경우 사과 드리며,이를 수행 할 수있는 대안을 제안합니다.
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???");
});
쉽게 걸릴 :
발견되지 않는 경우 신고하려면 부울을 사용할 수 있습니까? 따라서 "notFound = true;"와 같은 경고 대신 else 문에서 루프가 끝날 때 if (notFound) {// do stuff}를 검사하여 오류가 한 번만 발생하도록합니다. – zgood
@zgood 제안을 주셔서 감사합니다. 나는 지금 당장 그것을 시도 할 것이고 당신에게 돌아갈 것이다. – Abluescarab
@zgood 배열은 값의 유무에 관계없이 끝까지 반복됩니다. 루프를 멈추기 위해 "return"을 사용했지만 작동하지 않았습니다. – Abluescarab