小游戏存档管理
import userData from "userData";
export default {
mergeJSON(n, o) {
let oType = Object.prototype.toString.call(o);
let nType = Object.prototype.toString.call(n);
if (nType == '[object Object]' && oType == '[object Object]') {
for (let p in n) {
if (n.hasOwnProperty(p) && !o.hasOwnProperty(p)) {
o[p] = n[p];
} else if (n.hasOwnProperty(p) && (o.hasOwnProperty(p))) {
let oPType = Object.prototype.toString.call(o[p]);
let nPType = Object.prototype.toString.call(n[p]);
if ((nPType == '[object Object]' && oPType == '[object Object]') || (nPType == '[object Array]' && oPType == '[object Array]')) {
this.mergeJSON(n[p], o[p]);
}
};
}
} else if (nType == '[object Array]' && oType == '[object Array]') {
for (let i in n) {
let oIType = Object.prototype.toString.call(o[i]);
let nIType = Object.prototype.toString.call(n[i]);
if ((nIType == '[object Object]' && oIType == '[object Object]') || (nIType == '[object Array]' && oIType == '[object Array]')) {
this.mergeJSON(n[i], o[i]);
}
}
};
n = o;
return n;
},
updateUserData: function (localUserData) {
let now_ud = this.mergeJSON(userData, localUserData);
Object.assign(userData, now_ud)
cc.log(userData, "userData");
},
load: function () {
try {
let localUserData = JSON.parse(cc.sys.localStorage.getItem('userData'));
if (localUserData !== null) {
this.updateUserData(localUserData);
cc.log("使用存档");
} else {
this.save();
};
} catch (err) {
this.save();
cc.log("报错处理");
cc.log(err);
}
},
save: function () {
let cacheUserData = userData;
this.clear();
cc.sys.localStorage.setItem('userData', JSON.stringify(cacheUserData));
cc.log("已存档");
},
clear: function () {
cc.sys.localStorage.removeItem('userData');
},
};