2013-12-12 105 views
0

我正在學習編寫JavaScript代碼,並寫了這個代碼的ReferenceError:是沒有定義

var userAnswer = prompt("are you feeling lucky, punk?"); 
if (userAnswer === yes) 
{ 
console.log("Batman hits you very hard. It's Batman and you're you! Of course Batman wins!"); 
} 
else 
{ 
console.log("You did not say yes to feeling lucky. Good choice! You are a winner in the game of not getting beaten up by Batman."); 
} 

但是當我運行它,我得到 的ReferenceError:未定義肯定。

+3

'if(userAnswer ==='yes')'...... – Reimeus

+0

這不是java。 – Blub

回答

1

當您不用引號(即字符串文字)包含yes時,JavaScript會查找名稱爲yes的變量。您尚未定義名稱爲yes的變量,因此會引發錯誤。

添加引號這樣,以確定是否userAnswer包含字符串yes

if (userAnswer === 'yes') 

如果要接受不同的情況下(即YesYES),你可以使用.toLowerCase()

if (userAnswer.toLowerCase() === 'yes') 
0

你試圖比較變量userAnswer與另一個變量yes。問題是你還沒有定義yes。我相信你試圖比較userAnswer字符串文字「是」。

所以,如果你將userAnswer === yes更改爲userAnswer === "yes"它應該做你想做的。