gpt4 book ai didi

javascript - 如何在 javascript 中使用另一个函数中的变量

转载 作者:行者123 更新时间:2023-11-28 14:32:42 24 4
gpt4 key购买 nike

我无法从我的函数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 - 如何在 javascript 中使用另一个函数中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50882954/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com