如何删除localStorage中存储的对象的属性?

时间:2013-05-30 15:02:01

标签: javascript

在localStorage中我有一个对象记录。它有很多领域 记录[recordId],我希望能够删除这些条目。下面是我的删除功能,但它不起作用。所有记录仍附加到本地存储中的记录对象。不知道出了什么问题,因为我正在以正确的方式删除。当我打印记录对象时,所有记录仍然存在于它们的键????

function deleteLocalRecord(recordId) {
     var records = localStorage.getItem('records');
     var theRecords;
     if (supports_html5_storage()) {

          if (records == null) {
            theRecords = {};
          } else {
            // parse the records
            theRecords = JSON.parse(records);
          }

          theRecords[recordId] = '';  // set the record to empty string.
          delete theRecords[recordId]; // delete the record

          // reset the records object in local storage after change
          localStorage.setItem('records', JSON.stringify(theRecords));

     }
  }

  function supports_html5_storage() 
  {
    try 
    {
        return 'localStorage' in window && window['localStorage'] !== null;
    } 
    catch (e) 
    {
        return false;
    }
   }

1 个答案:

答案 0 :(得分:-1)

Live demo

function deleteLocalRecord(recordId) {
    if (localStorageEnabled()) {
        var records = localStorage.getItem('records'),
            theRecords  = JSON.parse(records) || {};

        print(JSON.stringify(theRecords)); // before
        delete theRecords[recordId]; // delete
        print(JSON.stringify(theRecords)); // after

        localStorage.setItem('records', JSON.stringify(theRecords));
        print(localStorage.getItem("records"));
    }
}

var records = {
    "test": "test",
    "stuff": "stuff"
};

localStorage.setItem("records", JSON.stringify(records));
deleteLocalRecord("test");


function print(x) {
    document.body.innerHTML += "<p>" + x + "</p>";
};

function localStorageEnabled() {
    return typeof window["localStorage"] !== "undefined";
};