Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do associative arrays don't work in localStorage[""]?

For example I have the following code:

  localStorage["screenshots"] = new Array();
  localStorage["screenshots"]["a"] = 9;
  alert(localStorage["screenshots"]["a"]);

  Arr = new Array();
  Arr["screenshots"] = new Array();
  Arr["screenshots"]["a"] = 9;
  alert(Arr["screenshots"]["a"]);

(I use Google Chrome v9.0.597.107 on Windows Vista 32-bit)

But only the second part works (output of alert() is "a")! The first alert outputs in contrast "undefined"!

What is the problem?

Thanks.

like image 871
ComFreek Avatar asked Mar 07 '11 15:03

ComFreek


1 Answers

localStorage stores values as strings, so you need to JSON serialize your objects on the way in and deserialize them on the way out. For example:

var data = {'A': 9};

localStorage['screenshots'] = JSON.stringify(data);

// Later/elsewhere:

var data = JSON.parse(localStorage['screenshots']);

// 9
console.log(data.A);
like image 108
Dave Ward Avatar answered Sep 20 '22 16:09

Dave Ward