0

I have an array in my code that changes value through a function.

var arr = [];

function arrfunction() {
arr.push(1);
}

I then change my HTML page to a different one using:

windows.location.replace("page2.html");

Since I change pages, my variable resets. I have tried to use sessionStorage to store arr, but I have to use JSON.stringify() to convert it into a string. The issue is, I need arr to remain as an array for later use.

Is there a way I can store my variable and also keep it as an array?

3 Answers3

2

Cant you just use JSON.parse() to turn the string back into a normal array and use sessionStorage?

fireking-design
  • 361
  • 1
  • 9
2

That is exactly how it works.

store:

const arr = [1];
sessionStorage.setItem("arr",JSON.stringify(arr)); // or localStorage

retrieve on other page:

const arr = JSON.parse(sessionStorage.getItem("arr")); // or localStorage
mplungjan
  • 169,008
  • 28
  • 173
  • 236
1

You can use JSON.parse to convert the stringify arr back to array.

For your reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse

Jin Tan
  • 518
  • 6
  • 19