Specify default value for HTML5 Local Storage item?

前端 未结 4 961
礼貌的吻别
礼貌的吻别 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: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';
    }
    

提交回复
热议问题