JavaScript for Kids 学习笔记6. 提示框

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

这些弹框的代码,也是可以直接在Chrome Console中运行的。


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);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值