javascript - 在网页上显示localstorage存储的数组元素

标签 javascript arrays json html local-storage

我能够成功存储 localStorage 的值并将其显示在 console.log() 中。由于这些值存储在 array 中,因此我无法使用 document.write 在我的 page 中显示它们。我希望存储的值显示在 page 上。有人可以建议一种方法吗?我的代码是:

// List of all entries
console.log(localStorage.getItem("total"));
// Last entry inserted
console.log(localStorage.getItem("intotal"));

document.write(total + "<br>"); // showing in console.log -> "Uncaught ReferenceError: allEntries is not defined "
document.write(intotal + "<br>"); // showing [object Object]

我不想将元素显示为:

 for(i=0; i< localStorage.length -1; i++)

因为,我有许多 localStorage 键/值 对,我不想显示所有 localStorage。我的意思是,我还将其他值存储在不同的键/对值中,例如:

 localStorage.setItem("Mymarks", (JSON.stringify(marks)); // where marks is JSON object
 localStorage.getItem("Mymarks");

因此,如果我使用 for 循环,那么 Mymarks/marks 键/对值也会显示在我的页面上。

我想要的输出与您在 console.log 中看到的相同。喜欢:

[{"name":"john","place":"asn"},"text":"abcd"},{"title":{"name":"john","place":"asn"},"text":"abcd"}] 

  {"name":"john","place":"asn"},"text":"abcd"}

最佳答案

好吧,我们不知道你想如何显示它们,但这是一种方式:

编辑

document.write("<pre>" + JSON.stringify(existingEntries) + "</pre>");    
document.write("<pre>" + JSON.stringify(entry) + "</pre>");

干杯,来自玻利维亚拉巴斯

关于javascript - 在网页上显示localstorage存储的数组元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20939608/

相关文章:

javascript - 如何在 Windows 上从 Python 执行 Javascript?

javascript - 未捕获类型错误 : Cannot set property 'innerHTML' of null in recaptcha_ajax. js

c++ - 将用户输入的 int 作为大小,将 int 作为数组,然后显示数组,最后一个索引到第一个索引

java - 由 : com. google.gson.JsonSyntaxException : java. lang.IllegalStateException 引起:预期为 BEGIN_OBJECT,但在第 1 行第 2 列处为 STRING

javascript - 将数据库和服务器添加到 javascript 引擎

javascript - 当 JSON 太长时 JSON.parse() 会抛出错误

javascript - 比较两个对象数组

javascript - 如何计算动态表每行总计

javascript - 通过key获取json数据

Javascript 如何将项目推送到对象中