我正在使用localStorage制作一个便笺web应用程序,当用户提交便笺时,来自input和textarea的值将保存在一个对象中。
创建的每个注释都是一个包含键/值对的对象
在创建新注释时,localStorage包含至少一个带有字符串的项之后,我将获取/检索localStorage字符串,该字符串将包含以前以字符串格式输入的注释。
>
每次将保存到输入对象中的新输入值推送到数组中,然后使用数组设置localstore项(当然是Stringify)。
下面是负责将注释保存到本地存储的函数
// 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
Array [ Object, Object, Object ]
相反,我得到:
Array [ Array[2], Object ]
代码笔:http://codepen.io/anon/pen/JdjMYq
看起来,当您将第一项保存到localstore(当那里什么都没有时)时,您只是将其保存为对象。然后,当您添加下一项时,将其包装在数组中。
相反,您可以保存包装在数组中的原始对象,然后将其推到该数组上:
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;
看到这个叉形密码笔了吗