JMA*_*JMA 8 javascript json local-storage
我有这个代码:
var string = '{"items":[{"Desc":"Item1"},{"Desc":"Item2"}]}';
localStorage.setItem('added-items', JSON.stringify(string));
Run Code Online (Sandbox Code Playgroud)
此代码将使用localStorage.
现在是获取存储数据的代码:
var retrievedObject = localStorage.getItem('added-items');
Run Code Online (Sandbox Code Playgroud)
我现在的问题是,我如何获得数据项的大小?答案必须是2.
我怎样才能得到"Item1"和"Item2"?
我试过retrievedObject[0][0]但它不起作用.
以及如何在其上添加数据?所以它会
{"items":[{"Desc":"Item1"},{"Desc":"Item2"},{"Desc":"Item3"}]}
Run Code Online (Sandbox Code Playgroud)
我可以用JSON.stringify吗?
var string = '{"items":[{"Desc":"Item1"},{"Desc":"Item2"}]}';
localStorage.setItem('added-items', JSON.stringify(string));
Run Code Online (Sandbox Code Playgroud)
stringify意思是,拿出object并将其作为一个回复string.你拥有的,已经是一个字符串,而不是一个JSON对象.
相反的是JSON.parse,它采取string并将其变成一个object.
它们都与获取数组的大小无关.正确编写JavaScript时,您几乎从不使用JSON.parse或JSON.stringify.仅在明确需要序列化时.
使用length该数组的大小:
var obj = {"items":[{"Desc":"Item1"},{"Desc":"Item2"},{"Desc":"Item3"}]}
console.debug(obj.items.length);
Run Code Online (Sandbox Code Playgroud)
小智 6
为了让未来的人们清楚地认识到这个问题,并发现公认的答案并不是你所希望和梦想的一切:
我扩展了问题,以便用户可能想要输入 astring或JSON到 中localStorage。
包括两个函数,AddToLocalStorage(data)和GetFromLocalStorage(key)。
对于AddToLocalStorage(data),如果您的输入不是 a string(例如JSON),那么它将被转换为 1。
GetFromLocalStorage(key)localStorage检索来自所述的数据key
脚本末尾显示了如何检查和更改 JSON 中的数据的示例。因为它是对象和数组的组合,所以在适用的地方必须使用.和的组合。[]
var string = '{"items":[{"Desc":"Item1"},{"Desc":"Item2"}]}';
var json = {"items":[{"Desc":"Item1"},{"Desc":"Item2"},{"firstName":"John"},{"lastName":"Smith"}]};
localStorage.setItem('added-items', AddToLocalStorage(string));
localStorage.setItem('added-items', AddToLocalStorage(json));
// this function converts JSON into string to be entered into localStorage
function AddToLocalStorage(data) {
if (typeof data != "string") {data = JSON.stringify(data);}
return data;
}
// this function gets string from localStorage and converts it into JSON
function GetFromLocalStorage(key) {
return JSON.parse(localStorage.getItem(key));
}
var myData = GetFromLocalStorage("added-items");
console.log(myData.items[2].firstName) // "John"
myData.items[2].firstName = ["John","Elizabeth"];
myData.items[2].lastName = ["Smith","Howard"];
console.log(myData.items[2]) // {"firstName":["John","Elizabeth"],"lastName":["Smith","Howard"]}
console.log(myData.items.length) // 4Run Code Online (Sandbox Code Playgroud)
小智 5
// THIS IS ALREADY STRINGIFIED
var string = '{"items":[{"Desc":"Item1"},{"Desc":"Item2"}]}';
// DO NOT STRINGIFY AGAIN WHEN WRITING TO LOCAL STORAGE
localStorage.setItem('added-items', string);
// READ STRING FROM LOCAL STORAGE
var retrievedObject = localStorage.getItem('added-items');
// CONVERT STRING TO REGULAR JS OBJECT
var parsedObject = JSON.parse(retrievedObject);
// ACCESS DATA
console.log(parsedObject.items[0].Desc);
Run Code Online (Sandbox Code Playgroud)