1. 创建一个 prompt
var name = prompt("What's your name?");
console.log("Hello " + name);
prompt("..." ); // 弹出一个带输入框的对话框
[cancel] [ok]
// 两个按钮
ok
// 点击OK,会返回输入框中的字符串
cancel
// 点击cancel,返回 null
这里讲到一个coercion 的概念,就是按照需要暗地里强制类型转换。点击cancel,会返回null,这个null本来是个特殊类型,不是字符串,但在字符串相加时,强制把它转成了字符串。
null -> "null"
2. 创建一个 confirm
var likesCats = confirm("Do you like cats?");
if (likesCats) {
console.log("You're a cool cat!");
}
else {
console.log("Yeah, that's fine. You're still cool!");
}
点击 ok , 返回true
点击 cancel, 返回false
3. 使用 alert
alert("JavaScript is awesome!");
4. 示例,猜字游戏
最后是一个猜字游戏。随机从数组中选一个单词,按字母个数显示一串下划线,如:_ _ _ _ _ _ 。弹框让玩家输入字母,如果输入的字母在单词中,则显示出来,如:m _ _ k e y 。如此反复,直到玩家猜出完整单词。把下面的代码复制到 Chrome console, 回车,运行,试一试吧。
// Create an array of words
var words = [
"javascript",
"monkey",
"amazing",
"pancake"
];
// Pick a random word
var word = words[Math.floor(Math.random() * words.length)];
// Set up the answer array
var answerArray = [];
for (var i = 0; i < word.length; i++) {
answerArray[i] = "_";
}
var remainingLetters = word.length;
// The game loop
while (remainingLetters > 0) {
// Show the player their progress
alert(answerArray.join(" "));
// Get a guess from the player
var guess = prompt("Guess a letter, or click Cancel to stop playing.");
if (guess === null) {
// Exit the game loop
break;
}
else if (guess.length !== 1) {
alert("Please enter a single letter.");
}
else {
// Update the game state with the guess
for (var j = 0; j < word.length; j++) {
if (word[j] === guess) {
answerArray[j] = guess;
remainingLetters--;
}
}
}
// The end of the game loop
}
// Show the answer and congratulate the player
alert(answerArray.join(" "));
alert("Good job! The answer was " + word);