简体   繁体   中英

Switch statement returning different results when called with same input in JavaScript

I'm writing a Linux "console emulator" as an easter egg for my website. I process the commands given using a switch statement, as such:

function processCommand(command) {
    var args = command.split(" ");
    console.log(args[0]);
    var res;
    switch(args[0]) {
        case "ls":
            res = ls($(".line.new .directory", args[1], args[2]).text());
            break;
        default:
            res = args[0] + ": command not found";
    }
    $(".line.new .response").html(res);
}

This is called by the following JQuery:

$(document).keydown(function(e) {
    ...
    else if(e.which == 13) {
        $(".line.new").append('<div class="response"></div>');
        processCommand($(".line.new .input").text()); // <-------------
        $(".line").removeClass("new").addClass("old");
        $(".main").append(...);
    }
});

When I give the input "ls" the first time, everything behaves as expected, however when run a second time, the switch goes to the default case. The value returned by console.log(args[0]) on line 3 is still the same.

Am I doing something wrong?

Edit :

Fiddle: https://jsfiddle.net/L90burfq/

If you check the length of args[0] , you will see that it is 2 characters the first time, and 3 characters the second time.

Modify your switch to trim any white-space before checking cases and it will work:

switch(args[0].trim())

See this https://jsfiddle.net/wkjy7du2/ .

var args = command.split(" ");
    var arg =args[0];
    var res;
    switch(arg.trim()) {
        case "ls":
  1. its have some extra space for second time click.so use with trim()
  2. Better declare as new variable for switch validate

If you add console.log({command}); you see that starting with the second invocation of the function, the value of command starts with \\r (a carriage-return character).

As a general rule you should trim command before splitting it into words, otherwise it fails even on the first invocation when its value starts with a space.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM