【问题标题】:Storing localStorage data in an array将 localStorage 数据存储在数组中
【发布时间】:2014-01-22 23:16:52
【问题描述】:

我将response 存储在localStorage 中并检索它的值。我的responsejson 格式。 response 会根据用户输入而变化。示例response 是:

      {
       "Name": "robert",
       "Number": "555-555-1234"
      }

我正在存储、检索和显示response 为:

     localStorage.setItem("response", JSON.stringify(response));
     var myResponse = localStorage.getItem("response");
     console.log(myResponse);

目前它正在向我显示最新的response,并且所有以前的response 都将被替换。如何将response 存储在array 中,以便可以存储我得到的所有response。比如:

  [ 
   {
       "Name": "robert",
       "Number": "555-555-1234"
   },
   {
       "Name": "john",
       "Number": "555-555-9999 Ext. 123"
   },
   {
       "Name": "albert",
       "Number": "555-555-8765"
   },
   {
       "Name": "jhony",
       "Number": "555-555-3098"
   },
   .
   .

 ]

【问题讨论】:

    标签: arrays json html local-storage


    【解决方案1】:

    改为存储和检索序列化数组:

    // Retrieving
    var responses = JSON.parse(localStorage.responses || "null") || [];
    
    // Adding a response
    responses.push(response);
    
    // Saving the array
    localStorage.responses = JSON.stringify(responses);
    

    如果您愿意,也可以使用getItem/setItem

    // Retrieving
    var responses = JSON.parse(localStorage.getItem("responses") || "null") || [];
    
    // Adding a response
    responses.push(response);
    
    // Saving the array
    localStorage.setItem("responses", JSON.stringify(responses));
    

    成语

    var responses = JSON.parse(localStorage.responses || "null") || [];
    

    或许可以用一些解释:

    1. 如果我们尝试检索本地存储中不存在的内容,我们会返回 null。 JavaScript 有一个curiously-powerful || operator:它不是返回布尔值,而是返回左侧参数,如果该参数为真,则返回其右侧参数。所以localStorage.responses || "null" 将是来自本地存储的字符串,或者如果没有,则为字符串"null"

    2. 然后我们解析结果,它要么是我们之前存储的序列化数组,要么是字符串"null"。尽管字符串 "null" 不是有效的 JSON 文档,但它一个有效的 JSON 片段,并且 JSON.parse 被记录为接受片段。所以解析的结果要么是我们之前存储的数组,要么是null

    3. 然后我们再次使用强大的 || 运算符在反序列化结果和空白数组 ([]) 之间进行选择。所以如果我们反序列化null,我们会选择[];如果我们反序列化一个数组,我们就会得到它。


    这是一个完整的工作示例;它所做的只是在上面的基本操作周围放置一些 UI:Live Copy | Live Source

    <!DOCTYPE html>
    <html>
    <head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
    <meta charset=utf-8 />
    <title>Complete Example</title>
      <style>
        .response {
          cursor: pointer;
        }
      </style>
    </head>
    <body>
      <div id="container"></div>
      <input type="text" id="responseInput">
      <input type="button" id="addResponse" value="Add">
      <script>
        (function() {
          // Get the responses (if any) or an empty array
          var responses = loadResponses();
    
          // Show the existing responses
          var container = $("#container");
          $.each(responses, function(index, response) {
            showResponse(response);
          });
    
          // Wait for user to add new ones
          var responseInput = $("#responseInput");
          responseInput.focus();
          $("#addResponse").click(function() {
            var text = $.trim(responseInput.val()),
                response = {
                  text: text,
                  id:   +new Date()
                };
            if (text) {
              responses.push(response);
              showResponse(response);
              saveResponses();
              responseInput.val("").focus();
            }
          });
    
          // Delete responses on click
          container.on("click", ".response", function() {
            var $this = $(this),
                id = parseInt($this.attr("data-id"), 10),
                index;
            $this.remove();
            if (id) {
              for (index = 0; index < responses.length; ++index) {
                if (responses[index].id === id) {
                  responses.splice(index, 1);
                  saveResponses();
                  break;
                }
              }
            }
          });
    
          function loadResponses() {
            return JSON.parse(localStorage.responses || "null") || [];
          }
    
          function saveResponses() {
            localStorage.responses = JSON.stringify(responses);
          }
    
          function showResponse(response) {
            $("<div>")
              .addClass("response")
              .text(response.text)
              .attr("data-id", response.id)
              .appendTo(container);
          };
        })();
      </script>
    </body>
    </html>
    

    【讨论】:

    • 你是先告诉getitem然后再告诉set吗?
    • @user2567857:我只是展示了您通常想要执行的三个操作,而不一定是说您会像这样一个接一个地执行它们。我可能会在页面加载时抓取数组,然后在每次更改时保存它。
    • 您的方法显示错误 - [object Object],[object Object] 如果我使用 document.write 来显示结果
    • @user2567857:不要使用document.write。使用调试器。我添加了一个活生生的例子,以防万一。但基本操作正是:非常基本。第一个代码块中的三个单行代码显示了如何执行每个基本操作。
    • @Crowder 我认为responseresponses 之间出现了一些问题。你能用responsemyResponse修改代码吗,正如我在问题中所展示的那样,否则我会感到困惑
    猜你喜欢
    • 1970-01-01
    • 2012-04-28
    • 2013-09-04
    • 1970-01-01
    • 1970-01-01
    • 2011-03-21
    • 2020-03-27
    • 2020-09-25
    • 2012-04-02
    相关资源
    最近更新 更多