简体   繁体   English

在javascript中使用JSON在localStorage中存储数组

[英]Storing array in localStorage with JSON in javascript

I have refereed this question and worked for me: so q1 我已经审问了这个问题,并为我工作: 所以q1

Now Issue is that I have used JSON.stringify & JSON.parse to store array in localStorage. 现在问题是我使用JSON.stringify&JSON.parse在localStorage中存储数组。 But when I run the code again and try to use JSON.parse on localStorage nothing get retrived. 但是当我再次运行代码并尝试在localStorage上使用JSON.parse时,没有任何东西可以重新获得。 I dont know whats going wrong. 我不知道什么是错的。

here is code: 这是代码:

    function BankProDisplay() {
        var myString = JSON.parse(localStorage['bankpro']);
        var mySplitResult = myString.split(",");
        for (i = 0; i < mySplitResult.length; i++) {
            document.getElementById('bankpro').innerHTML = document.getElementById('bankpro').innerHTML + mySplitResult[i] + "<br/>";
        }
    }

If you store an Array in LocalStorage using JSON.stringify, then you get it back using JSON.parse, return value is Array, not string. 如果使用JSON.stringify在LocalStorage中存储一个数组,那么使用JSON.parse返回它,返回值是Array,而不是string。 So when you are using function mySplitResult for myString (which is actually Array, thanks to JSON.parse), then it leads to an Error. 因此,当您使用函数mySplitResult for myString(实际上是Array,感谢JSON.parse)时,它会导致错误。 So remove function mySplitResult and it should work fine. 所以删除函数mySplitResult,它应该工作正常。

var myString = JSON.parse(localStorage['bankpro']);

JSON.parse返回一个javascript对象,而不是一个字符串,它没有split方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM