0

I am building a website and can't understand how to pass arrays across different web pages of the same website. The code for defining the array is:

sessionStorage.setItem("hello", JSON.stringify(["hi", "sup"]));

The code for calling the array on the second page is:

var helloArray = JSON.parse(sessionStorage.getItem("hello"));

When I loop through the array with this code:

for (var i = 0; i < helloArray.length; i++) {
  // JavaScript code
}

It creates an error that says: Uncaught TypeError: Cannot read property 'length' of null.

What can I change and what did I do wrong?

Weafs.py
  • 22,731
  • 9
  • 56
  • 78
sam tam
  • 11
  • 2
  • 1
    Maybe you want `localStorage` instead? From the [**documentation**](https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Storage#sessionStorage): *"This is a global object (`sessionStorage`) that maintains a storage area that's available for the duration of the page session. A page session lasts for as long as the browser is open and survives over page reloads and restores. Opening a page in a new tab or window will cause a new session to be initiated."* – Felix Kling Nov 27 '14 at 00:18
  • Sessions should really only be used to store strings. They're unreliable with other forms of information. Try storing it as a string and recovering it as a hash/JSON. – steel Nov 27 '14 at 01:10
  • oh my gosh! your idea worked Felix Kling. you are my hero! – sam tam Nov 27 '14 at 01:23
  • possible duplicate of [Storing Objects in HTML5 localStorage](http://stackoverflow.com/questions/2010892/storing-objects-in-html5-localstorage) – nramirez Nov 27 '14 at 14:32

1 Answers1

2

Use localStorage like this:

- To write content:

localStorage.setItem("hello", JSON.stringify(["hi", "sup"]));

- To read content:

var helloArray = JSON.parse(localStorage.getItem('hello'));

Here JSFiddle!

Winner Crespo
  • 1,644
  • 15
  • 29