将多个localStorage阵列添加到普通阵列

时间:2014-10-30 18:25:05

标签: javascript html arrays local-storage

大家好我有一个问题。我制作了一个日历,一切正常,但最后一个要求是通过localStorage添加日期。

所以我的问题是:如何在不覆盖第一个日期的情况下添加更多日期? 我在考虑获取数据,添加新的testObject,并将其重新发送到localStorage。唯一的问题是我不知道该怎么做。

我希望有人可以提供帮助。 (我是初学者)

简而言之,我希望通过events将多个数组放入localStorage - 数组中。


这是我的代码:

<script language="JavaScript" type="text/javascript" >
    testObject = ["Y", prompt("maand"), prompt("dag"), "2000", prompt("test"), prompt("test")]
    retrievedObject = localStorage.getItem('testObject');

    // Put the object into storage
    localStorage.setItem('testObject', JSON.stringify(testObject))



events = new Array(
          JSON.parse(retrievedObject),
        ["Y",   "1",    "1",    "2000",     "Nieuw jaars dag",  "De eerste dag van het nieuw Jaar"],
        ["Y",   "7",    "3",    "2000",     "Mijn verjaardag", "beste dag van het jaar"],
        ["Y",   "17",   "10",   "2000",     "Inleverdag",   "Ergste dag van het jaar."]
    );
</script>

编辑:在我添加2个数组后,它应该像这样工作但是应该从本地存储中检索上面的2个值,如果我添加另一个,那么它应该是本地存储中的3个数组。但是本地存储每次都会覆盖自己所以此刻我只能添加1个数组

events = new Array(
        ["Y",   "1",    "2",    "2000",     "test", "test"],

         ["Y",  "2",    "4",    "2000",     "test2",    "test3"],
        ["Y",   "1",    "1",    "2000",     "Nieuw jaars dag",  "De eerste dag van het nieuw Jaar"],
        ["Y",   "7",    "3",    "2000",     "Mijn verjaardag", "beste dag van het jaar"],
        ["Y",   "17",   "10",   "2000",     "Inleverdag",   "Ergste dag van het jaar."]
    );

1 个答案:

答案 0 :(得分:1)

我认为您的措辞存在困惑,您在询问如何将数据添加到数组中,但您提供的代码示例根本不会添加任何内容。

我认为你的追随者是Array.prototype.pushArray.prototype.concat

为了展示和示例,我将对您想要做的事做出以下假设:

// Helper to easily create a new test object
function buildTestObject() {
  return [
    'Y',
    prompt('maand'),
    prompt('dag'),
    '2000',
    prompt('test'),
    prompt('test')
  ];
}

// Pull in the old value from localStorage
var retrievedObject = localStorage.getItem('testObjects') || '[]';

try {
  // Turn JSON into JS Object
  retrievedObject = JSON.parse(retrievedObject);
} catch (e) {
  retrievedObject = [];
}

// Actually add a testObject to the array which will be stored in localStorage
retrievedObject.push(buildTestObject());

// Save the now mutated array of testObjects back into localStorage
localStorage.setItem('testObject', JSON.stringify(retrievedObject))

var events = retrievedObject.concat(
  ["Y",   "1",    "1",    "2000",     "Nieuw jaars dag",  "De eerste dag van het nieuw Jaar"],
  ["Y",   "7",    "3",    "2000",     "Mijn verjaardag", "beste dag van het jaar"],
  ["Y",   "17",   "10",   "2000",     "Inleverdag",   "Ergste dag van het jaar."]
);