Appending localStorage with dynamic content

Clash Royale CLAN TAG#URR8PPPAppending localStorage with dynamic content
I am generating image coordinates at various locations within a image which I am saving to a localStorage item. For example:
var coords = ;
coords.push(Math.round(dragStopLocation.x),Math.round(dragStopLocation.y));
The above stores the values in coords variable. I am setting this to localStorage using:
localStorage.setItem('coords', JSON.stringify(coords));
This as a standalone code works well.
Since, the item coords is dynamic and many arrays of coords is possible, I want to append the item coords with new arrays. I am using the following code:
coords
coords
coords
//Save the original coords items in a variable
var old_coords = localStorage.getItem('coords');
//append
if (old_coords === null) {
localStorage.setItem('coords', JSON.stringify(coords));
} else {
localStorage.setItem('coords', old_coords + JSON.stringify(coords));
}
I tried one more variation of this by including a comma between old_coords and coords
localStorage.setItem('coords', old_coords + ',' + JSON.stringify(coords));
The problem I am facing is when I am trying to get the items of the coords from a different function.
function getArray() {
items = JSON.parse(localStorage.getItem('coords'));
var size = 9;
var newarr = ;
for (var i = 0; i < items.length; i+=size) {
newarr.push(items.slice(i, i+size));
}
return newarr;
}
This is were I am facing the following error:
Uncaught SyntaxError: Unexpected token [ in JSON at position 4
When I use a comma, I get the same error but instead of '[ I get ,.
[
,
I tried replicating this with a simple example:
localStorage.removeItem('items');
function appendToStorage(name, data){
var old = localStorage.getItem(name);
if(old === null || old === undefined) {
localStorage.setItem(name,data);
} else {
localStorage.setItem(name, old +"," + data);
}
}
items1 = ['image1','place','name',10,20,30,40,50,60];
appendToStorage('items', items1);
localStorage.getItem('items');
items2 = ['image2','place','name',11,21,31,41,51,61]
appendToStorage('items', items2);
localStorage.getItem('items');
This works perfectly...however the original code gives errors.
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.