class Utils {
// 内部定义的标识
static STORAGE_PREFIX = 'myApp_';
// 生成 UUID
static generateUUID() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = (crypto.getRandomValues(new Uint8Array(1))[0] % 16) | 0;
var v = c == 'x' ? r : (r & 0x3) | 0x8;
return v.toString(16);
});
}
// 存储数据到本地,使用内部定义的标识
static storeDataToLocalStorage(key, value) {
const storedKey = `${Utils.STORAGE_PREFIX}${key}`;
try {
localStorage.setItem(storedKey, JSON.stringify(value));
console.log(`Data stored with key: ${storedKey}`);
} catch (error) {
console.error('Error storing data to localStorage:', error);
}
}
// 从本地读取数据,使用内部定义的标识,并提供默认值
static readDataFromLocalStorage(key, defaultValue) {
const storedKey = `${Utils.STORAGE_PREFIX}${key}`;
try {
const storedValue = localStorage.getItem(storedKey);
if (storedValue) {
return JSON.parse(storedValue);
} else {
// 如果没有找到数据,返回默认值,并选择性存入
console.log(`No data found with key: ${storedKey}, returning default value.`);
Utils.storeDataToLocalStorage(key, defaultValue); // 将默认值存入
return defaultValue;
}
} catch (error) {
console.error('Error reading data from localStorage:', error);
return defaultValue; // 如果读取出错,也返回默认值
}
}
}
// 使用示例:
const defaultUserData = { name: 'Default User', age: 0 };
// 尝试读取数据,如果没有则存入默认值
const retrievedData = Utils.readDataFromLocalStorage('user', defaultUserData);
console.log(retrievedData); // 输出从 localStorage 读取的数据或默认值
正文完
好好