我很好奇为什么这不会引起我的问候。代码:
function myNameWelcome(userName, thought) {
var greeting = "Welcome pardner, so your're name is " + userName + ". " + thought;
return greeting;
}
myNameWelcome("Peter", "Shine on you crazy diamond.");
alert(greeting);
答案 0 :(得分:1)
您的返回值未分配给该功能之外的任何内容。
答案 1 :(得分:1)
greeting
超出了范围。它是在函数内部定义的,因此在您调用alert(greeting);
的范围内不可用。解决这个问题很容易:
var greeting;
function myNameWelcome(userName, thought) {
greeting = "Welcome pardner, so your're name is " + userName + ". " + thought;
}
myNameWelcome("Peter", "Shine on you crazy diamond.");
alert(greeting);
甚至更好:
function myNameWelcome(userName, thought) {
return "Welcome pardner, so your're name is " + userName + ". " + thought;
}
var greeting = myNameWelcome("Peter", "Shine on you crazy diamond.");
alert(greeting);
答案 2 :(得分:0)
因为greeting
是本地变量,只能在 myNameWelcome
中访问。它不存在于函数之外。
请参阅What is the scope of variables in JavaScript?以了解有关变量范围的更多信息。