如何将多个前置日期存储到 localStorage?

How do I store multiple prepended dates to localStorage?

我正在尝试将当前时间和日期存储在 table 中。目前,在页面加载时,我的代码会更改日期以反映当前时间。

我的代码如下所示:

function currentDate() {
  var d = new Date();
  return d.toString();
}
window.onload = function() {
   localStorage.setItem("date", currentDate());
   $('#current-location').prepend('<tr<td>'+localStorage.getItem("date")+'</td>');
}

我试过console.log(localStorage),所以我知道那里保存了一个日期。但是,我想存储重新加载页面时的日期(比如第二次加载页面并出现 2 个日期等)我需要一个数组吗?如果是这样,我如何将数组内容添加到 table?

是的,您可以为此使用一个数组,然后继续将日期推送到数组,就像这样

function currentDate() {
  var d = new Date();
  return d.toString();
}

var arr = JSON.parse(localStorage.getItem("date") || "[]");

arr.push(currentDate())

localStorage.setItem("date", JSON.stringify(arr));

arr.forEach(function(item) {
  $('#current-location').prepend('<tr><td>' + item + '</td></tr>');
});

FIDDLE

所以,我将添加一个对象作为 JSON 并将其字符串化版本保存到 localStorage 中。作为概念证明,您可以使用这样的东西:

1) 初始化localStorage中的对象:

var listOfDates = {
  dates: []
};
localStorage.setItem('myDates', JSON.stringify(listOfDates));

根据您的需要,您可能希望将其放入 "if(!localStorage.getItem('myDates'))"

2) 创建一个读取存储的函数,解析 JSON,向 dates 数组添加一个项目,然后保存回 localStorage:

addDateRowToTable = function() {

  var listOfDates = JSON.parse(localStorage.getItem('myDates'));
  listOfDates.dates.push(currentDate());
  localStorage.setItem('myDates', JSON.stringify(listOfDates));

  for(var i=0; i< listOfDates.dates.length; i++) {
   // do whatever you need to
  }
}

希望对您有所帮助。