2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

localStorageにJSON化して Get & Set

Last updated at Posted at 2013-12-21
storage(key,val)
/**
 * localStorageにJSON化して Get & Set
 * keyにnull、valにkeyを設定すれば Remove
 */
function storage(key, val) {
  var v = JSON.parse(localStorage.getItem(
    (key === null) ? val : key
  ));
  if (key === null)
    localStorage.removeItem(val);
  else if (arguments.length >= 2)
    localStorage.setItem(key, JSON.stringify(val));
  return v;
}

Array#popは削除してなおかつ削除した値を返すので、これもそんな感じにしたかった。

SetするときもRemoveするときも必ず元の登録されていた値を返します。

// Get & Set
storage('foo', 'bar'); // null
// Get
storage('foo'); // 'bar'
// Get & Remove
storage(null, 'foo'); // 'bar'
// Get
storage('foo'); // null

参考:DOM Storage - DOM | MDNlocalStorageを使いこなすための覚え書き | misc

2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?