lundi 21 mars 2016

Trying to return a value from a function in a switch statement -JS-

I'm trying to make switch statements that can answer some questions that I add it to it . I want the answers end with the user's name , so if you typed in the prompt "My name is Alex" it will save Alex in the "var username ;" I want the "username" has the value even before defined the "sendUserName" function.

<html>

<body>
<script>
var ask = prompt ("Ask me anything >>").toLowerCase ();
function write (x){document.write(x)};
//Capitalize the first letter func :
function capitalize(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
//..............

var question = ask.split(" ");
var date = new Date ;
var userName ;
   //...............................
   write(userName);  // <------ here the issue , undefined !
if (question[0] === "what"){

switch ( question[1]){
    case "time":
                switch (question[2]){
                    case "is":
                              switch (question[3]){
                              case "it":
                              write(date);
                              break;
                              default:
                              };
                    break;
                default:    
                } ;
     break;
    case "is":
              switch (question[2]){
                  case "your" :
                               switch (question[3]){
                               case "name":
                               write("Alex !");
                               break;
                               default:
                               };
                  break;
                  default:

              };
    break;

default: write("unknown");

};

}
else if (question[0] === "my"){

switch (question[1]){
    case "name":
               switch(question[2]){
                   case "is":

                    userName = capitalize(question[3]);;
                    alert("Your name is saved, "+userName);
                    function sendUserName(){

                        return userName ;
                    }
                   break;

                  default: 
               };
    break;



    default:
};
};
sendUserName();
write(userName); // <------- it's work here
</script>


</body>

</html>

Aucun commentaire:

Enregistrer un commentaire