如何在javascript中使用其他函数的变量 [英] How can I use variables from another function in javascript

查看:68
本文介绍了如何在javascript中使用其他函数的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法从我的函数访问我的变量 UserInfo 我的所有变量都是未定义的。如何访问我的变量并在我的函数中显示它们 seeInfoUser

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 function seeInfoUser

let UserName;
let UserAge;
let UserBirthPlace;
let UserDream;  

let UserInfo = function(){
  let UserName = prompt("What is your name:");
  let UserAge = prompt("How old are you: ");
  let UserBirthPlace = prompt("Where were you born: ")
  let 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)


推荐答案

你在 UserInfo 中重新声明您的变量,这会导致它们隐藏已在更高范围内声明的变量。只需在函数内的变量赋值中删除 let 关键字,这样就可以使用已经声明的变量,而不是重新声明较小的范围变量。

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)

这篇关于如何在javascript中使用其他函数的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆