Specify default value for HTML5 Local Storage item?

前端 未结 4 969
礼貌的吻别
礼貌的吻别 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: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.

提交回复
热议问题