简体   繁体   中英

JSON.parse error Javascript

A problem. Again. Here is the code:

if(localStorage.getItem("temporaryArray")){
    var temporaryArray = JSON.parse(localStorage.getItem("temporaryArray"));
}else{
    var temporaryArray = [];
}

So basically what it does is that when a new page is loaded I don't want to reset the array because later in the code I assign something to this array in localStorage. So what I'm trying to say is that if you can get this item, then when the code is loaded again assign this variable to the localStorage item. Else, just set it to an empty array. But here is the error I'm getting because the array is currently empty(I think that's the reason why):

Uncaught SyntaxError: Unexpected token o in JSON at position 1
    at JSON.parse (<anonymous>)
    at main.js:61

Any help would be very much appreciated.

If a method invocation fails, it usually helps to look at what the input to the function is. I would recommend doing console.log(localStorage.getItem("temporaryArray")) before the JSON.parse() call to see what the problem is.

What I would guess the source of the problem is, is that at some point you are calling localStorage.setItem("temporaryArray",value) and have forgotten to do JSON.stringify() on the value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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