Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: store an array of integers locally so they can be accessed elsewhere?

This may be a really quick answer (or a really stupid question), but I'm trying to store an array of integers so that they can be accessed later locally by another function, at a random time.

Ways I have thought of so far to do this (and their flaws):

  • HTML5 data attributes i.e. data-ids="1,2,3" (can't store an array easily in these)
  • HTML5 localStorage (can only store a string, not an array and would have to convert)
  • a hidden input i.e. <input type="hidden"> (again, can't store an array, have to convert into a string)

Ideally I would like to be able to push values onto this locally stored array with syntax like array.push(value) etc.

Is there an easy way to do this that I'm missing or will I be resorting to hacks? The end use of this array will be comparing with another array of integers to see if any values match, and if there is a match, remove the index from the second array (i.e. it's an array filter).

This array shouldn't be stored on the server because it is different for each user on the client-side. If there is no nice way to do this I'll probably just think about implementing the functionality a different way.

like image 244
wnajar Avatar asked Nov 17 '25 10:11

wnajar


2 Answers

You could, of course, just use window.somevarname = [1,2,3]

Alternatively, if by "elsewhere" you mean on a completely different pageload, then your best bet would be to run it through JSON.stringify() and drop it in localStorage, then JSON.parse() it out.

like image 120
Niet the Dark Absol Avatar answered Nov 19 '25 00:11

Niet the Dark Absol


Just declare a global variable in your html head section

<script type="text/javascript">
var MyGlobalVariable = [1,2,3];
// or window.MyGlobalVariable = [1,2,3];
</script>

Now you can access it throughout the page.

like image 25
Nagarjun Avatar answered Nov 18 '25 23:11

Nagarjun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!