Change key value in localStorage?

蹲街弑〆低调 提交于 2019-12-31 01:25:48

问题


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

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

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


回答1:


You can take a look at the official specification.

The storage interface looks like this:

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

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.



来源:https://stackoverflow.com/questions/20862054/change-key-value-in-localstorage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!