← 第 2 关 – 魔法师

第 3/8 课 ⏱ 30 分钟

变量和条件

教页面记住东西并做决定。这是编程的核心。

跟我看:变量——程序的记忆

变量 是带标签的盒子,程序在里面存值:

let clickCount = 0;        // number
let name = "Jake";         // string (text)
let isWeekend = true;      // true/false

变量可以做数学、可以改:

clickCount = clickCount + 1;   // increase by 1
clickCount++;                  // same thing, shorter

跟我看:点击计数器

把变量和上一课的按钮结合起来:

<button id="counter">Clicked: 0×</button>
const counter = document.getElementById("counter");
let count = 0;

counter.addEventListener("click", () => {
  count++;
  counter.textContent = "Clicked: " + count + "×";
});

页面第一次 记住了东西。每次点击增加盒子里的数字并显示。

跟我看:条件——做决定

条件 说:“如果这是真的,做 A。否则,做 B。”

if (count >= 10) {
  counter.textContent = "Ten clicks! You've got some serious stamina 🏆";
} else {
  counter.textContent = "Clicked: " + count + "×";
}

轮到你了 💪

做一个带惊喜的计数器:点击到一定次数后,发生额外的事。

🏫 学校网站——投票选最好吃的食堂菜
<h2>Vote for pizza day!</h2>
<button id="vote">Vote 🍕 (0 votes)</button>
<p id="result"></p>
const vote = document.getElementById("vote");
const result = document.getElementById("result");
let votes = 0;

vote.addEventListener("click", () => {
  votes++;
  vote.textContent = "Vote 🍕 (" + votes + " votes)";

  if (votes >= 5) {
    result.textContent = "Decided! Pizza day wins the election. 🏆";
  }
});
🙋 个人网站——颠球计数器
<h2>How many times can I juggle the ball?</h2>
<button id="kick">Kick! (0)</button>
<p id="record"></p>
const kick = document.getElementById("kick");
const record = document.getElementById("record");
let kicks = 0;

kick.addEventListener("click", () => {
  kicks++;
  kick.textContent = "Kick! (" + kicks + ")";

  if (kicks === 20) {
    record.textContent = "20 kicks – new personal record! 🎉";
  }
});
🌍 旅行日记——去过的国家计数
<h2>Country counter</h2>
<button id="country">Add a country (0)</button>
<p id="rating"></p>
const country = document.getElementById("country");
const rating = document.getElementById("rating");
let countryCount = 0;

country.addEventListener("click", () => {
  countryCount++;
  country.textContent = "Add a country (" + countryCount + ")";

  if (countryCount >= 10) {
    rating.textContent = "Ten countries – you're a globetrotter! 🌍";
  } else if (countryCount >= 5) {
    rating.textContent = "Five countries – beginner traveler. 🎒";
  }
});

注意 else if——这样可以把多个条件串起来。

⚽ 俱乐部网站——射门记分
<h2>Shooting practice</h2>
<button id="goal">GOAL! ⚽</button>
<p id="score">Score: 0</p>
const goal = document.getElementById("goal");
const score = document.getElementById("score");
let goals = 0;

goal.addEventListener("click", () => {
  goals++;

  if (goals >= 10) {
    score.textContent = "Score: " + goals + " – hat trick and more! Player of the match 🏆";
  } else {
    score.textContent = "Score: " + goals;
  }
});
💡

你刚刚学了真正的编程。 变量和条件不只是”网页东西”——在 Python、游戏和应用里完全一样。会变量和条件的人,能和世界上任何编程语言对话。

检查一下: 计数器在数,到上限后会有额外效果。试着大声逐行解释代码在做什么——能做到,基础就掌握了。

这堂课你要记住