指定HTML5本地存储项的默认值? [英] Specify default value for HTML5 Local Storage item?

查看:110
本文介绍了指定HTML5本地存储项的默认值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果您尝试获取不存在的本地存储项,是否可以为该项设置默认值?

In the case that you are trying to get a local storage item that doesn't exist, is it possible to set a default value for that item?

例如,假设在您的Web应用程序中,各种UI首选项都保存在本地存储中。当用户离开您的网站然后返回时,将根据从其本地存储中提取的值设置UI。这非常有用。

For example, let's say that in your web app, various UI preferences are saved in local storage. When a user leaves your website and then comes back, the UI is setup according to the values pulled from their local storage. This works great.

但是,当用户第一次访问您的Web应用程序时,这些本地存储值尚不存在。因此,当您的JavaScript尝试获取这些本地存储项时,它们都将是未定义的。是否有办法在每个本地存储项不存在的情况下为每个本地存储项指定默认值?

However, when a user visits your web app for the first time, those local storage values do not exist yet. So when your JavaScript attempts to get those local storage items, they will all be undefined. Is there not a way to specify default values for each local storage item in the case that it doesn't exist?

大多数处理保存键/值对的编程语言提供一些指定默认值的方式(想想.ini配置文件接口)。我期待这样的事情:

Most programming languages that deal with saving key/value pairs offer some sort way to specify default values (think .ini config file interfaces). I was expecting something like this:

var preference = localStorage.getItem('some-key', 'Default Value');

另外,我知道我可以通过测试它们是否为null / undefined来轻松地以编程方式设置默认值。不要,并相应地设置值,但我想看看这是否内置于本地存储键/值对提取,也许我只是没有看到它。如果这个功能不存在,我最后会写一些基本的本地存储包装函数来添加这个功能。

Also, I know that I can easily programmatically set default values by testing if they are null/undefined or not and set the value accordingly, but I wanted to see if this was built into the local storage key/value pair fetching and that maybe I just wasn't seeing it. If this feature doesn't exist, I will end up just writing some basic local storage wrapper functions that add in this feature.

推荐答案

不,没有这样的内置功能。请参阅 存储界面

No, there is no such built-in functionality. See the spec for the Storage interface:

interface Storage {
  readonly attribute unsigned long length;
  DOMString? key(unsigned long index);
  getter DOMString getItem(DOMString key);
  setter creator void setItem(DOMString key, DOMString value);
  deleter void removeItem(DOMString key);
  void clear();
};

以下行只是为了进一步确认:

And the following line just to confirm that further:


getItem(key)方法必须返回与给定键关联的当前值。如果与对象关联的列表中不存在给定键,则此方法必须返回null

The getItem(key) method must return the current value associated with the given key. If the given key does not exist in the list associated with the object then this method must return null.

你可以使用通常的技巧。这样的事情应该没问题:

You can just use the usual techniques. Something like this should be fine:

var preference = localStorage.getItem('some-key') || 'Default Value';

这篇关于指定HTML5本地存储项的默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆