Specify default value for HTML5 Local Storage item?

前端 未结 4 959
礼貌的吻别
礼貌的吻别 2020-12-18 19:15

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?

For example, let\'s say that in

相关标签:
4条回答
  • 2020-12-18 19:21

    You can use this method for objects

    /*
    Helper function that return an object from local storage or a default value
    */
    function getObjectFromLocalstorage(key, default_value){
      var value = localStorage.getItem(key);
      if (value === null){
        return default_value;
      }
      return JSON.parse(value);
    }
    

    And here are some example outputs:

    console.log(getObjectFromLocalstorage("some_undefined_key", {}));
    >>> {}
    
    console.log(getObjectFromLocalstorage("some_undefined_key", []));
    >>> []
    
    var value = {a: 1}; 
    localStorage.setItem("defined_key", JSON.stringify(value));
    getObjectFromLocalstorage("defined_key", {});
    >>> {a: 1}
    
    0 讨论(0)
  • 2020-12-18 19:29

    The solution from James:

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

    Only works if you never save empty strings OR booleans OR if your variable can be 0.

    Solution which is longer but always works:

    var preference = localStorage.getItem('some-key');
    if(null === preference)
    {
        preference = 'Default Value';
    }
    
    0 讨论(0)
  • 2020-12-18 19:34

    If you have to use json objects, this is a clean way of doing it:

    const defaultPreferences = {
      darkMode: true,
      language: 'es',
    };
    
    // Read, with fallback to default value
    let preferences = JSON.parse(localStorage.getItem('preferences')) || defaultPreferences;
    

    And this is how you have to save to localStorage:

    preferences.language = 'fr';
    
    // Write, always in JSON
    localStorage.setItem('preferences', JSON.stringify(preferences));
    

    Note: Remember to save to localStorage every time you modify the preferences variable, to maintain consistency.

    0 讨论(0)
  • 2020-12-18 19:48

    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:

    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';
    
    0 讨论(0)
提交回复
热议问题