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.

1

2 Answers 2

1

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

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

1 Comment

I use objects to store other variables but I want to achieve this with named arrays particularly.
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.

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.