为什么您需要使用一种方法来访问 localStorage,例如:
localStorage.setItem('name', 'content');
一个允许像这样的API
localStorage.name = 'content';
会更容易使用。还有为什么它只允许字符串?
最佳答案
An API that allowed something like
localStorage.name = 'content';
would be much easier to work with.
确实如此。如果您愿意,可以使用它代替 setItem
。来自 the specification :
The supported property names on a
Storage
object are the keys of each key/value pair currently present in the list associated with the object.
这样做的缺点是它不能在不支持本地网络存储的浏览器上填充,而 setItem
/getItem
API 可以。
Also how come it only allows strings?
因为这是最简单的事情。简单的 API 实现起来更容易、更快,也更容易测试(请记住,目标是让多个 vendor 快速支持这一点——而且它奏效了)。如果您需要更丰富的东西,您可以使用 JSON 或 XML 或您喜欢的任何其他形式,序列化为字符串或从字符串序列化。就像 HTTP。
关于javascript - 为什么 localStorage 不能作为对象访问?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31489746/