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.
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.
Share Improve this question asked Mar 7, 2011 at 15:21 ComFreekComFreek 29.4k18 gold badges107 silver badges157 bronze badges 6 | Show 1 more comment3 Answers
Reset to default 17localStorage 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);
The localStorage
object can only store strings. To store other types of data, use must convert them to strings, and convert them back on retrieval. In most cases you would want to use JSON to do this.
Local storage only stores string keys and string values.
The DOM Storage mechanism is a means through which string key/value pairs can be securely stored and later retrieved for use.
Source: MDC.
new Object()
or object literal syntax{}
, which are associative arrays. – Matt Ball Commented Mar 7, 2011 at 16:10length
property or (integer-indexed) array methods. The basic methods are, as I understand it (and Wikipedia seems to agree with me):add
,reassign
,remove
, andlookup
. See also this article. – Matt Ball Commented Mar 7, 2011 at 16:39