解析检索到的localStorage项会在控制台中带来不希望的结果

时间:2015-04-23 05:55:10

标签: javascript json local-storage

我正在使用localStorage制作一个笔记web应用程序,当用户提交一个笔记时,输入和textarea中的值将保存在一个对象中。

创建的每个注释都是包含键/值对的对象

  • id:0
  • title:输入值
  • 内容:来自textarea的价值

在创建新笔记之后,localStorage包含至少一个带有字符串的项目后,我获取/检索localStorage字符串,该字符串将包含过去以字符串格式输入的笔记。

  1. 解析localStorage字符串并将其保存到变量/数组中,以便添加先前的注释。

  2. 每次将新输入值保存到输入对象中,然后在使用数组设置localStorage项目之前将其推送到数组中(当然,将其字符串化)。

  3. 以下是负责将笔记保存到localStorage

    的功能
        // User clicks to save note
        post_note_button.onclick = function() {
    
        // Get values from input and textarea
        var note_title = document.getElementById("note-title").value;
        var note_textarea = document.getElementById("note-textarea").value;
    
        // Each time note is created, new values from input will be saved
        var input = { id: note_id_count, title: note_title, content: note_textarea };
    
        // ------------------------------------------------
    
        switch(localStorage.getItem("note")) {
    
            // If retrieve for localStorage item returns false/doesn't exist
            // PURPOSE: Set localStorage string for first time
            // 1. Create localStorage item with values from user's input
            case null:
                localStorage.setItem("note", JSON.stringify(input));
            break;
    
            // If retrieve for localStorage item returns true/exists
            // PURPOSE: To retrieve localStorage string and manipulate it
            // 1. Changing localStorage string, requires string to be retrieved and saved as array
            // 2. Add item to array
            // 3. Create/set localStorage item with values from array, convert to string
            default:
                var note_array = [JSON.parse(localStorage.getItem("note"))];
                console.log(note_array);
    
                note_array.push(input);
    
                localStorage.setItem("note", JSON.stringify(note_array));
            break;
        }
    
        // ------------------------------------------------ 
    };
    

    我的问题: 当我 console.log&在添加几个笔记后解析 localStorage项目“note”,我应该

    Array [ Object, Object, Object ]
    

    相反,我得到:

    Array [ Array[2], Object ]
    

    codepen:http://codepen.io/anon/pen/JdjMYq

1 个答案:

答案 0 :(得分:0)

看起来当您将第一个项目保存到localStorage时(当没有任何内容时),您只是将其保存为对象。然后,当您添加下一个项目时,将其包装在一个数组中。

相反,你可以保存包裹在数组中的原始对象,然后只需按下那个:

case null:
  localStorage.setItem("note", JSON.stringify([input]));
  break;

-

default:
    var note_array = JSON.parse(localStorage.getItem("note"));
    console.log(note_array);

    note_array.push(input);

    localStorage.setItem("note", JSON.stringify(note_array));
    break;

请参阅此https://support.google.com/webmasters/answer/6073543?hl=en