是否可以在LocalStorage中使用ES6符号 [英] Is it possible to use ES6 Symbols in LocalStorage
问题描述
在将ES6 Symbol
用作LocalStorage
中键/值对的键时,在重新加载页面后我们还能访问它吗?
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?
我发现了本教程声称使用Symbol.for
时这是可能的,但是到目前为止,当我尝试检索LocalStorage键/值对时,我仍然没有成功并获得undefined
.
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.
作为附带的问题:在这里使用Symbols
是否有意义?
As a side question: does it make sense to use Symbols
over here?
推荐答案
您可以将Symbols用作对象中的键-这最终是它们的目的.但是localStorage
不是您的典型对象.它具有一个API,用于设置/获取商店中的值,您共享的教程未使用该API:localStorage.{set,get}Item()
.
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()
.
不幸的是,localStorage
不接受将Symbols作为键,而仅将字符串作为键.因此,真正的答案是否定的,您不能在本地存储中使用符号作为键,但是...
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...
您可以执行以下操作.它实际上不是使用Symbol作为键,而是Symbols toString()
表示形式:
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))
作为附带的问题:在此处使用符号是否有意义?
As a side question: does it make sense to use Symbols over here?
我想您可以使用保留的符号(例如Symbol.iterator
)来扩展localStorage
全局功能.但这不是重点.
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.
这篇关于是否可以在LocalStorage中使用ES6符号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!