最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Converting string back to an array from local storage - Stack Overflow

programmeradmin7浏览0评论

Im probably miles off but can anyone tell me if this is possible.

 function myFunction(){

 var myArray = (localStorage.getItem("storedArray"));
 myArray = jQuery.makeArray( myArray );

 myArray.push(['someone@myemail','15','myUsername']);
 localStorage.setItem("storedArray", JSON.stringify(grabArray));

 localStorage.removeItem("storedArray");

 }

Every time this function is ran i'm wanting to get an array from local storage push values to it and then store it back, so like updating it. The idea is that once an event happens in my application, this item will be cleared, to start logging again.

When i've got the item from local storage i've attempted to turn it back into an array but i don't think this is the way to do it as it isn't returning anything. Can anything be done with JSON?

Thanks.

Im probably miles off but can anyone tell me if this is possible.

 function myFunction(){

 var myArray = (localStorage.getItem("storedArray"));
 myArray = jQuery.makeArray( myArray );

 myArray.push(['someone@myemail','15','myUsername']);
 localStorage.setItem("storedArray", JSON.stringify(grabArray));

 localStorage.removeItem("storedArray");

 }

Every time this function is ran i'm wanting to get an array from local storage push values to it and then store it back, so like updating it. The idea is that once an event happens in my application, this item will be cleared, to start logging again.

When i've got the item from local storage i've attempted to turn it back into an array but i don't think this is the way to do it as it isn't returning anything. Can anything be done with JSON?

Thanks.

Share Improve this question asked Apr 22, 2015 at 22:36 jord49jord49 5822 gold badges18 silver badges40 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4
function myFunction() {
            var storedArray = JSON.parse(localStorage.getItem("storedArray"));

            if (storedArray === null) {
                storedArray = [];
            }

            var obj = {
                email: "[email protected]",
                age: 15,
                name: "username"
            };

            storedArray.push(obj);
            localStorage.setItem("storedArray", JSON.stringify(storedArray));
        }

Setting the updated storedArray to same key in local storage overwrites the old value. Try this code and you'll see the updated array.

Info: Local Storage data is stored as key-value.

Trott was right, you missed to parse the json that you saved.

JSON.stringify converts your json object/array into a string. In order to get back the same data you have to parse it.

If you are using JSON.stringify() to convert the object to a JSON string representation, then you can use JSON.parse() to convert the JSON representation back to the object.

发布评论

评论列表(0)

  1. 暂无评论