🧪 Lab Practice Note实验练习笔记

Consolidated guidance for completing Week 1 Git & JavaScript lab activities. 汇总第1周 Git 与 JavaScript 实验活动的操作要点与技巧。

📋 Lab Overview实验概览

Use this note as a quick reference before or during the lab. Each section highlights the commands, reasoning, and collaboration habits expected in tutorials. 本笔记可在实验前或实验中快速参考,涵盖命令、思路与协作习惯,帮助你在课堂上高效完成任务。

Focus Areas重点关注

  • Git workflow: add → commit → pushGit 工作流:add → commit → push
  • Commit messaging and upstream tracking提交信息与上游跟踪设置
  • Pulling remote updates in collaboration drills协作练习中的远程更新拉取
  • JavaScript objects and timestamp handlingJavaScript 对象与时间戳处理

What You’ll Gain完成后你将掌握

  • Confidence with everyday Git commands熟练掌握日常 Git 命令
  • Ability to sync work when teammates push changes能在队友推送后快速同步代码
  • Comfort modelling data with JS objects熟悉用 JS 对象建模数据
  • A clear checklist before submitting lab work提交实验前的自查清单

🌿 Git Lab Warm-upGit 实验热身

Core Workflow核心流程

  • Stage changes: git add filename暂存更改git add filename
  • Commit with context: git commit -m "message"提交并写明含义git commit -m "message"
  • Push to remote: git push推送至远端git push

Key Concepts重要概念

  • -m flag: keep commit descriptions short but informative.-m 参数:提交信息要短而清晰。
  • Upstream tracking: git push -u origin main for the first push so future git push works alone.上游跟踪:首次推送使用 git push -u origin main,之后直接 git push 即可。
  • Status check: run git status before and after committing.状态检查:提交前后都运行 git status

Collaboration Drill协作演练

Simulate a teammate updating the repository to practise pulling safely. 模拟队友更新仓库,练习安全地拉取最新代码。

  1. Edit a file directly on GitLab (remote)在 GitLab(远程)上直接编辑文件
  2. Return to local repo and run git pull回到本地仓库执行 git pull
  3. Verify the update landed before continuing work确认更新已同步后再继续开发

⚙️ JavaScript Object PracticeJavaScript 对象练习

Week 1 labs emphasise modelling state with plain objects. Keep the following patterns handy. 第1周实验强调使用普通对象描述状态,下面的模式可以随手参考。

Object Basics对象基础

// Object literal
const profile = {
  name: 'John Doe',
  age: 25,
  createdAt: 1234567890
};

Remember: dot syntax for reading/updating, and spread syntax for cloning. 牢记:用点语法读取/更新,用展开语法克隆对象。

Timestamp Operations时间戳操作

// Current Unix timestamp (seconds)
const now = Math.floor(Date.now() / 1000);

// Human readable helper
function formatTimestamp(ts) {
  return new Date(ts * 1000).toISOString();
}

Mnemonic: “JavaScript gives milliseconds, divide by 1000 for seconds.” 记忆:“JS 给的是毫秒,除以 1000 变成秒”。

Naming & Validation Patterns命名与校验模式

  • Follow camelCase: first word lowercase, later words capitalised (e.g. updatedAt).遵循驼峰命名:首词小写,其余首字母大写(如 updatedAt)。
  • Use the in operator to confirm property existence: 'updatedAt' in profile.使用 in 操作符确认属性存在:'updatedAt' in profile
  • Keep numeric fields numeric—avoid accidental string interpolation for values like age.保持数字字段为数字,避免用模板字符串生成如 age 这类数值。

Implementation Cheat Sheet实现速查

profileCreate()profileCreate()

Builds a profile object with name, age, and created timestamp. 创建带姓名、年龄与创建时间的档案对象。

function profileCreate(nameFirst, nameLast, birthYear) {
  const currentYear = new Date().getFullYear();
  const timestamp = Math.floor(Date.now() / 1000);

  return {
    name: `${nameFirst} ${nameLast}`,
    age: currentYear - birthYear,
    createdAt: timestamp
  };
}
  • Template literals combine names cleanly.模板字符串便于拼接姓名。
  • Return numeric age via subtraction, not strings.通过减法返回数字年龄,避免字符串。
  • Always store Unix timestamps in seconds.统一使用秒级 Unix 时间戳。

profileCompareAge()profileCompareAge()

Returns a positive, negative, or zero value when comparing ages. 比较两人年龄,返回正数/负数/零。

function profileCompareAge(profile1, profile2) {
  return profile1.age - profile2.age;
}
  • Direct subtraction keeps the implementation concise.直接相减实现精简。
  • Useful when sorting profiles by age.适合按年龄排序档案。

profileUpdateName()profileUpdateName()

Updates the name field and stamps the modification time. 更新姓名并记录更新时间。

function profileUpdateName(profile, newName) {
  profile.name = newName;
  profile.updatedAt = Math.floor(Date.now() / 1000);
}
  • Mutates in place—no return value required.原地修改,不需要返回值。
  • Recalculate timestamps on each update.每次更新都重新计算时间戳。

profileHasUpdate()profileHasUpdate()

Checks whether an update timestamp exists. 检查是否存在更新时间戳。

function profileHasUpdate(profile) {
  return 'updatedAt' in profile;
}
  • in works for own and inherited properties.in 适用于自有属性和继承属性。
  • Gate UI displays or status badges with this check.可根据此结果控制界面提示。

profileSerialise()profileSerialise()

Converts an object into a JSON string for storage. 将对象转换为 JSON 字符串以便存储。

function profileSerialise(profile) {
  return JSON.stringify(profile);
}
  • Remember: JSON.stringify → string.记住:JSON.stringify → 字符串。
  • Ideal for writing to files or APIs.适合写入文件或通过 API 传输。

profileDeserialise()profileDeserialise()

Restores JSON strings back into usable objects. 把 JSON 字符串还原为可用对象。

function profileDeserialise(profileString) {
  return JSON.parse(profileString);
}
  • JSON.parse performs the reverse of stringify.JSON.parse 是 stringify 的逆过程。
  • Wrap in try/catch if input might be invalid.输入不可信时可配合 try/catch

Common Mistakes常见错误

Property Names属性名

// ❌ Wrong
profile.updatedName = timestamp;

// ✅ Correct
profile.updatedAt = timestamp;

Keep naming consistent so downstream checks still work. 保持命名一致,避免后续检查失效。

Data Types数据类型

// ❌ String result
age: `${currentYear - birthYear}`;

// ✅ Numeric result
age: currentYear - birthYear;

Arithmetic should return numbers, not template strings. 算术运算应返回数字,而非模板字符串。

Timestamps时间戳

// ❌ Milliseconds
Date.now();

// ✅ Seconds
Math.floor(Date.now() / 1000);

Convert to seconds whenever storing Unix time. 存储 Unix 时间时务必转换为秒。

Key Takeaways重点总结

  1. Divide by 1000 whenever you convert Date.now() to Unix time.Date.now() 转为 Unix 秒时务必除以 1000。
  2. Stick to camelCase and descriptive property names.坚持使用驼峰命名和具象属性名。
  3. Use 'prop' in object to guard optional fields.通过 'prop' in object 校验可选字段。
  4. Remember the JSON.stringify/JSON.parse round-trip.牢记 JSON.stringify/JSON.parse 的往返流程。
  5. Avoid accidental strings when performing numeric logic.处理数字逻辑时避免误用字符串。

Lab Checklist & Tips实验清单与小贴士

  • Run git status until the working tree is clean before submission.提交前多次运行 git status,确保工作区干净。
  • Push one final commit with a descriptive message (e.g. "Finish lab 1 practical").最后推送一次带描述的提交(如 "Finish lab 1 practical")。
  • Take screenshots or notes for any tricky commands—handy for reflection tasks.遇到难点命令及时截图或记录,便于课后反思。
  • Sync to the latest remote state before you leave the lab.离开实验室前同步远程最新状态。