js中实现数据的本地存储和调用

我这里用一个游戏中的分数为例:

   1.全局中设置一个对象Container来存储数据  var Container = {};

   2.在对象中写两个接口存储数据和调用数据

 var Container = {     

              SetScore:function(value){

                   this.SetCookie("_GameScore", value);

              },
                        GetScore:function() {
                   return this.GetCookie('_GameScore');
              },  
            
              SetCookie: function (name, value) {
                   console.log("SetC", name, value);
                   var cookieDate = new Date();
                   var NextYearTime = cookieDate.getTime() + (365 * 86400 * 1000);
                   cookieDate.setTime(NextYearTime);
                   document.cookie = name + "=" + encodeURIComponent(value) + "; expires=" + cookieDate.toUTCString();
              },
             
              GetCookie:function(name){    
                 var cookie_array = {};
                 var cookie = document.cookie;
                 var cookie_sets = cookie.split(';');
                 for (var num in cookie_sets) {
                        var sets = cookie_sets[num].split('=');
                        var cookie_key = sets[0].replace(/^\s+|\s+$/g, '');
                        delete sets[0];
                        var cookie_value = sets.join('=');
                        cookie_value = cookie_value.replace(/^=/, "");
                        cookie_array[cookie_key] = decodeURIComponent(cookie_value);
                    }               
                 return cookie_array[name];
                }
	};

   3.在游戏中存取分数:Container.SetScore(TARGET_SCORE); TARGET_SCORE玩家当前获得的分数进行存储

4.获取分数:Container.GetScore(); 
如果有多个数据需要存取,只需要多设置一些存取的接口,通过存储code获取数据即可
4.4

你可能感兴趣的:(js)