我正在尝试使用localStorage,我仍在学习如何访问对象中的值。我已成功返回localStorage中的一堆对象,现在我想知道如何将这些逗号分隔的键值对变为清晰易读的格式。我已经尝试了replace
方法以及循环遍历该对象,但没有运气。我非常感谢你的帮助。
这是我的localStorage输出:
{"question":"How do you get close to the president?","your_answer":"buy him some chocolates","answer":"bribe your way in","check":false}{"question":"What is your code name?","your_answer":"John","answer":"Mikhalov","check":false}
我希望它看起来像这样:
Question #1: blahblah
Your Answer: blah
Check: Wrong
Question#2: ...
尝试#1:
if (counter == questions.length-1){
output = ''
for(var i =0; i < localStorage.length; i++){
output += localStorage.getItem(localStorage.key(i)).replace(/"{"/g,"\r\n");
}}
尝试#2
if (counter == questions.length-1){
for (var key in localStorage){
for (option in key){
console.log(option)
}
}
}
答案 0 :(得分:1)
var obj = [{"question":"How do you get close to the president?","your_answer":"buy him some chocolates","answer":"bribe your way in","check":false},{"question":"What is your code name?","your_answer":"John","answer":"Mikhalov","check":false}];
obj[0].question;
转换为数组。