How can I use variables from another function in javascript

后端 未结 2 936
孤街浪徒
孤街浪徒 2021-01-26 06:32

I cant have access to my variables from my function UserInfo all my variables are undefined. How can I have access to my variable and display them in my func

相关标签:
2条回答
  • 2021-01-26 06:38

    You are re-declaring your variables in UserInfo which causes them to hide the ones already declared in a higher scope. Just remove the let keyword on the variable assignments inside the function so that, instead of re-declaring smaller scoped variables, you use the already declared ones.

    // These variables will be available in the current scope and descendent scopes
    let UserName;
    let UserAge;
    let UserBirthPlace;
    let UserDream;  
        
    let UserInfo = function(){
      // ...So, don't re-declare the variables - just use them!
      UserName = prompt("What is your name:");
      UserAge = prompt("How old are you: ");
      UserBirthPlace = prompt("Where were you born: ")
      UserDream = prompt("What is your Greatest Dream: ");
    }
        
    let seeInfoUser = function (){
      // You really don't need to declare a variable if all you are going to do is return its value
      return ` ${UserName} is  ${UserAge} and he was born in ${UserBirthPlace} and his greatest dream is ${UserDream}`;
    }
        
    let result = seeInfoUser(UserInfo());
    console.log(result)

    0 讨论(0)
  • 2021-01-26 07:04

    The issue with your code is the scope of the variables. In javascript, all variables declared with let have block scope. And you are redeclaring them inside your UserInfo function, so you should just use the variables you had already declared.

    let UserName;
    let UserAge;
    let UserBirthPlace;
    let UserDream;
    
    
    let UserInfo = function() {
      UserName = prompt("What is your name:");
      UserAge = prompt("How old are you: ");
      UserBirthPlace = prompt("Where were you born: ")
      UserDream = prompt("What is your Greatest Dream: ");
    }
    
    let seeInfoUser = function() {
    
      let UserInformation = ` ${UserName} is  ${UserAge} and he was born in ${UserBirthPlace} and his greatest dream is ${UserDream}`
    
      return UserInformation
    }
    
    
    
    let result = seeInfoUser(UserInfo());
    console.log(result)

    0 讨论(0)
提交回复
热议问题