0

I have named arrays that I want store in local storage.

For example:

testla=[];

testla['aaaa']='a';

However, when I try:

console.log(JSON.stringify(testla));

This outputs:

[]

And even more weird, when using:

testla=[];

testla[10]='a';

I get strange results like this:

[null,null,null,null,null,null,null,null,null,null,"a"]

According to docs, localstorage can only store strings, therefore stringifying makes sense to me, but apparently it doesn't work, so there must be other way of doing this.

Anonymous
  • 4,692
  • 8
  • 61
  • 91
  • _"I have named arrays"_ - no you don't, because that's not a thing. http://stackoverflow.com/questions/874205/what-is-the-difference-between-an-array-and-an-object – CBroe May 13 '17 at 22:15

2 Answers2

1

JSON.stringify() ignores non-array properties of arrays. But you can use objects: var testla = {}; .

Alex
  • 59,571
  • 22
  • 137
  • 126
1

In the first example you are just adding a property call aaa to your object. Same as

testla.aaaa = 'foo';

You can create an associative array by using an object as so :

var myArr = {};
myArr['aaaa'] = 'bar';

There is no such thing as a named array, arrays in js can only be indexed using numbers.

dashton
  • 2,684
  • 1
  • 18
  • 15