JS how to cache a variable

后端 未结 5 1250
一生所求
一生所求 2020-12-04 14:37

What I want to do is to be able to create a variable, give it a value, close and reopen the window, and be able to retrieve the value I set in the last session. What is the

5条回答
  •  自闭症患者
    2020-12-04 15:04

    Use localStorage for that. It's persistent over sessions.

    Writing :

    localStorage['myKey'] = 'somestring'; // only strings
    

    Reading :

    var myVar = localStorage['myKey'] || 'defaultValue';
    

    If you need to store complex structures, you might serialize them in JSON. For example :

    Reading :

    var stored = localStorage['myKey'];
    if (stored) myVar = JSON.parse(stored);
    else myVar = {a:'test', b: [1, 2, 3]};
    

    Writing :

    localStorage['myKey'] = JSON.stringify(myVar);
    

    Note that you may use more than one key. They'll all be retrieved by all pages on the same domain.

    Unless you want to be compatible with IE7, you have no reason to use the obsolete and small cookies.

提交回复
热议问题