Skip to content

Todo 数据 Model

中等 约 30 分钟

你将构建什么

`todos` 数组的 任务对象 `{ id, title, 做 }` plus three pure 函数: `addTodo`, `toggleTodo`, and `listTodos` 那个操作 on 数组.

学习目标

  • Model 真实-世界 entity (任务) as 对象
  • Use 数组 as 集合 and mutate 它 safely
  • 编写函数那个 take 状态 and 返回新 状态
  • 练习唯一-id generation 使用计数器

前置要求

  • 对象 and 属性 access
  • 数组 and 数组方法 (推送, 映射, 查找)
  • 函数使用参数

步骤

  1. 1

    定义任务 shape

    Decide 什么单个任务 looks 如. minimal 任务有 id (数字), title (字符串), and 做 (布尔值). 编写 helper makeTask(id, title) 那个返回 such 对象所以每个任务是 shaped consistently.

    代码
    function makeTask(id, title) {
      return { id, title, done: false };
    }

    预期结果

    makeTask(1, "Learn loops") 返回 { id: 1, title: "Learn loops", 做: 假 }.

  2. 2

    设置集合

    创建 todos 数组 and nextId 计数器开始 at 1. 计数器 guarantees 每个任务获取唯一 id 偶数之后 deletions.

    代码
    let todos = [];
    let nextId = 1;

    预期结果

    空列表 and 计数器 ready 到 assign id 1 到首先任务.

  3. 3

    Implement addTodo

    编写 addTodo(title) 那个创建任务使用 current nextId, pushes 它到 todos, increments nextId, and 返回新 任务. Returning 任务 lets caller know 什么是 添加.

    代码
    function addTodo(title) {
      const task = makeTask(nextId, title);
      todos.push(task);
      nextId++;
      return task;
    }

    预期结果

    addTodo("Buy milk") 返回任务 and todos 现在有 长度 1.

  4. 4

    Implement toggleTodo

    编写 toggleTodo(id) 那个查找任务通过 id and flips 它的 做 flag. 如果 id 是不 找到, 返回消息. 查找通过 id 是 safer than 通过 title 因为 titles 能 repeat.

    代码
    function toggleTodo(id) {
      const task = todos.find(t => t.id === id);
      if (!task) return "Task not found";
      task.done = !task.done;
      return task;
    }

    预期结果

    之后切换 id 1, 那个任务's 做 flag flips 从假 到真.

  5. 5

    Implement listTodos and 测试

    编写 listTodos() 那个返回 readable 列表的 所有任务. 然后添加 three 任务, 切换 one, and print 列表到 确认 model 工作端-到-端.

    代码
    function listTodos() {
      return todos.map(t =>
        `[${t.done ? "x" : " "}] #${t.id} ${t.title}`
      );
    }
    
    addTodo("Learn loops");
    addTodo("Write calculator");
    addTodo("Build todo model");
    toggleTodo(2);
    console.log(listTodos());

    预期结果

    Three 行 printed: 任务 #2 shows [x], others show [ ].

自己动手试试

你学到了什么

你 modeled 真实 feature as 数据 (对象 in 数组) plus 操作 (函数), and used 计数器 for 唯一 ids — 相同 shape used 通过 production todo apps, 只是使用 UI on 顶部.

相关资源

相关课程

  • 对象

    对象 represent 每个任务 in model.

  • 数组

    数组 and 方法如 推送, 查找, and 映射 drive 集合.

  • 函数

    函数 encapsulate 操作 on model.

相关练习

相关工具

  • JSON Formatter

    Inspect todos 数组 as 格式化 JSON — 精确地如何它 会是 存储.

相关速查表

相关参考文档

相关错误

相关术语

相关术语

新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。

相关错误

用大白话解释常见错误——什么意思、为什么发生、如何修复。

← 返回主题