更改localStorage中的键值? [英] Change key value in localStorage?

查看:507
本文介绍了更改localStorage中的键值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为1且包含something的localStorage项目。

I have a localStorage item named as "1" and containing "something".

我想将名称更改为2并保持内容不变。我怎么能这样做?

I want to change the name to "2" and leave the contents intact. How can I do that?

我知道我可以将整个内容复制到2然后删除1但是还有其他直接方法吗?

I know that I can copy the entire contents to "2" and then delete "1" but is there any other direct method?

推荐答案

你可以看看官方规范

存储界面如下所示:

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();
};

如您所见,没有移动或重命名方法。因此,更改数据键的唯一方法是使用 getItem 从旧密钥中获取数据, setItem 将它放到新密钥和 removeItem 以删除旧密钥。

As you see, there is no move- or rename method. So the only way to change the key of data is by using getItem to get the data from the old key, setItem to put it to the new key and removeItem to remove the old key.

当你觉得经常需要更改密钥,您应该重新考虑您用作密钥的信息是否真的适合这项工作。

When you feel the frequent need to change keys, you should reconsider if the information you use as key is really suitable for the job.

这篇关于更改localStorage中的键值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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