I want to save 5 button coordinates to localStorage
then retrieve them for a click event to identify when a button is clicked. Centre coordinates for the buttons are saved to an array as they are rendered. When the object is retrieved I can only access them as a single character string rather than as an array.
How do I save them as an array ? and how do I retrieve them ?
I'm not sure if what I want to do is even possible as this is the first idea I have for using JSON
. The idea came from looking at this answer which made me ask if this could be a way to store and receive a set of floating point numbers. So I'd be most grateful if anyone can point me in the right direction.
during render
var xButtonCoords = [];
var yButtonCoords = [];
xButtonCoords.push(button.x.toPrecision(6));
yButtonCoords.push(button.y.toPrecision(6));
Once rendering is done coordinates are saved to localStorage
.
store(xButtonCoords, yButtonCoords);
The store
function packs button coordinates as a string object before it is stored.
function store(xButtonCoords, yButtonCoords) {
var xCoords = packString(xButtonCoords, xButtonCoords.length); // show just x coordinate
localStorage.setItem('xCoords', JSON.stringify(xCoords)); // put into storage
The packString
function represents button coordinates as a string before putting the object into storage. The string object uses a key value pair.
function packString(points, numberOf) {
var coords = [];
for (i = 0; i < numberOf; i++) { // do number of shifts
var key = i; // make a coordinate key
var val = points.shift(); // get coordinate value
var string = key+" : "+val; // create key value string
coords.push(string); // save string as coords
}
return coords;
}
during event
var X = localStorage.getItem('xCoords'); // retrieve from storage
var report = 'xDots: '+JSON.parse(X);
alert(report);
The retrieved object appears as a string of characters.
NB. The five string character integers in the key represent the order in which buttons are rendered. I am trying to create an array of 5 floating point numbers not a string of characters.
for (var [key, value] of Object.entries(report)) {
alert(`${key}: ${value}`); // characters not elements
}
}