![](/img/trans.png)
[英]How do I use variables and function from another file in javascript?
[英]How can I use variables from another function in javascript
我无法从我的函数UserInfo
访问变量,所有变量均未定义。 如何访问变量并将其显示在函数中, 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
关键字,即可使用已声明的变量,而不是重新声明较小的作用域变量。
// 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中,用let
声明的所有变量都具有块作用域。 并且您在UserInfo
函数中重新声明了它们,因此您应该只使用已经声明的变量。
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.