如何在if else语句中声明变量?

时间:2015-07-23 21:02:27

标签: javascript if-statement

var user = prompt("what is your name?");
if (user == "joe")  {
  var game = "what's up joe"
}
if (user == "alex") {
  var game = "hello alex how are you"
}
else {
  game = "sorry don't know you"
}

var other = alert(game);

由于某些原因,这不起作用我想让游戏等于许多不同的东西。如果我使用超过3个if语句游戏总是等于最后一个。有人可以帮助我吗?

3 个答案:

答案 0 :(得分:3)

在if语句之外声明“游戏”并使用它。

var user = prompt("what is your         name?");
var game = "";
if (user == "joe")  {
  game = "what's up joe"
} else if (user == "alex") {
  game = "hello alex how are you"
} else {
  game = "sorry don't know you"
}

var other = alert(game);

答案 1 :(得分:1)

你不能:No such thing as block scope in JavaScript

可能是关于该主题的最佳文章:JavaScript Scoping and Hoisting

答案 2 :(得分:0)



var user = prompt("What is your Name?");
var auth = "joe";
if (user == auth) {
  alert("Whats Up ")+ user;
};
else if(user != auth | user!=="alex"){
  alert("I dont Know you! ")+ user;
};
else {
  alert("Error!");
};