返回課程

儲存已讀日期

重要性:5

有一個訊息陣列,如同在 前一個任務 中。

let messages = [
  {text: "Hello", from: "John"},
  {text: "How goes?", from: "John"},
  {text: "See you soon", from: "Alice"}
];

現在的問題是:你會建議使用哪個資料結構來儲存「訊息已讀時間」的資訊?

在前一個任務中,我們只需要儲存「是/否」的事實。現在我們需要儲存日期,而且它只應保留在記憶體中,直到訊息被垃圾回收為止。

附註:日期可以儲存在內建 Date 類別的物件中,我們稍後會介紹。

要儲存日期,我們可以使用 WeakMap

let messages = [
  {text: "Hello", from: "John"},
  {text: "How goes?", from: "John"},
  {text: "See you soon", from: "Alice"}
];

let readMap = new WeakMap();

readMap.set(messages[0], new Date(2017, 1, 1));
// Date object we'll study later