简体   繁体   中英

How can I make the value be equal to localstorage or default to “0”

I am getting a value like this:

CreatedBy = localStorageService.get('selectedCreatedBy');

How can I make it default to "0" if there is nothing in local storage?

你有这样尝试吗:

CreatedBy = localStorageService.get('selectedCreatedBy') || 0;
var value = localStorage.getItem("key");

var result = value === null ? 0 : value;

https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Storage#localStorage

see definition of localStorage.getItem(), if the value is not stored. getItem() return null

Here is an extremely simplified version of a localStorage wrapper library I wrote a year ago that allows default values to be passed (also does JSON encoding/decoding of values). Outside of using something like this you are going to have to check each time you retrieve a value from localStorage that the value is not null as the other answerers have pointed out.

var storage = {
    get: function(key, default_value){
        var response = localStorage.getItem(key);
        response = response || default_value || null;
        if(response){
            try{
                response = JSON.parse(response);
            } catch(e) {}
        }
        return response;
    },
    set: function(key, value){
        if(typeof value.charAt !== 'function'){
            value = JSON.stringify(value);
        }
        localStorage.setItem(key, value);
        return this;
    }
}

storage.set('foo', {a: 'b', c: 'd'});

storage.get('bar'); // returns null
storage.get('bar', [1, 2, 3]); // returns array [1,2,3]
storage.get('foo'); // returns Object {a: "b", c: "d"}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM