【cococos creator】localStorageメモリ、データ読み出し、jsonと文字列変換

10921 ワード

localStorageストレージデータ
userData:データ名JSON.stringify(userData):jsonファイル(データであってもよい)
var userData={id:Id,//ID name:Name,//名前};cc.sys.localStorage.setItem(‘userData’, JSON.stringify(userData));
読み込み:
        var str = cc.sys.localStorage.getItem('userData');//    
        var userData = JSON.parse(str);//  json  id
        this.name = userData.name;//    
        this.id = userData.id;//  id
// Learn cc.Class:
//  - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/class.html
//  - [English] http://docs.cocos2d-x.org/creator/manual/en/scripting/class.html
// Learn Attribute:
//  - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/reference/attributes.html
//  - [English] http://docs.cocos2d-x.org/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/life-cycle-callbacks.html
//  - [English] https://www.cocos2d-x.org/docs/creator/manual/en/scripting/life-cycle-callbacks.html

cc.Class({
    extends: cc.Component,

    properties: {
        // foo: {
        //     // ATTRIBUTES:
        //     default: null,        // The default value will be used only when the component attaching
        //                           // to a node for the first time
        //     type: cc.SpriteFrame, // optional, default is typeof default
        //     serializable: true,   // optional, default is true
        // },
        // bar: {
        //     get () {
        //         return this._bar;
        //     },
        //     set (value) {
        //         this._bar = value;
        //     }
        // },
    },

    // LIFE-CYCLE CALLBACKS:

    onLoad() {
        this.name = "";
        this.id = 0;
        this.readMsg();
    },

    start() {

    },

    save: function () {
        this.saveMsg(this.id, this.name);
    },

    saveMsg: function (Id, Name) {
        var userData = {
            id: Id,
            name: Name,
        };
        cc.sys.localStorage.setItem('userData', JSON.stringify(userData));//   
    },

    readMsg: function () {
        if (cc.sys.localStorage.getItem('userData') ) {
            var str = cc.sys.localStorage.getItem('userData');//    
            str = str.replace(/\ +/g, "");//    
            str = str.replace(/[\r
]/g
, "");// var userData = JSON.parse(str); this.name = userData.name; this.id = userData.id; } else { this.save(); } } // update (dt) {}, });

jsonと文字列変換
JSON.stringify()      JavaScript       JSONJSON.parse()   JSON

削除
window.localStorage.removeItem('key')
//    
//window.localStorage.clear()