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?

4
  • 1
    Maybe you want localStorage instead? From the documentation: "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." Commented Nov 27, 2014 at 0: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. Commented Nov 27, 2014 at 1:10
  • oh my gosh! your idea worked Felix Kling. you are my hero! Commented Nov 27, 2014 at 1:23
  • possible duplicate of Storing Objects in HTML5 localStorage Commented Nov 27, 2014 at 14:32

1 Answer 1

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!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.