Is it possible to use ES6 Symbols in LocalStorage

2020-04-11 05:30发布

When using a ES6 Symbol as the key for a key/value pair in LocalStorage, can we then still access it after reloading the page?

I found this tutorial that claims this to be possible when using Symbol.for, but so far I have no success and get an undefined when I try to retrieve the LocalStorage key/value pair.

As a side question: does it make sense to use Symbols over here?

1条回答
Root(大扎)
2楼-- · 2020-04-11 06:00

You can use Symbols as keys in an object - that's ultimately their purpose. But localStorage is not your typical object. It has an API to set/get values in the store, which the tutorial you have shared is not using: localStorage.{set,get}Item().

Unfortunately localStorage doesn't accept Symbols as keys, only strings. So the real answer is no, you can't use Symbols as keys in LocalStorage, but...

You could do the following. It isn't actually using a Symbol as the key, but the Symbols toString() representation:

const sym = Symbol.for('Hello').toString()
localStorage.setItem(sym, 'World')
document.write('Hello, ' + localStorage.getItem(sym))

[ Check it out on jsbin.com ]

As a side question: does it make sense to use Symbols over here?

I suppose you could use reserved Symbols (e.g. Symbol.iterator) to extend the functionality of the localStorage global. But that's kind of besides the point.

查看更多
登录 后发表回答