/** * 本地存储管理类 */ export class LocalStorageManager { private test1(): void { // 存储数据 LocalStorageManager.setItem("playerName", "Tom"); LocalStorageManager.setItem("playerLevel", 5); LocalStorageManager.setItem("playerData", { score: 100, level: 3 }); // 获取数据 const name = LocalStorageManager.getItem("playerName"); const level = LocalStorageManager.getItem("playerLevel"); const data = LocalStorageManager.getItem<{ score: number, level: number }>("playerData"); console.log(name); // 输出: Tom console.log(level); // 输出: 5 console.log(data); // 输出: { score: 100, level: 3 } // 删除某项 LocalStorageManager.removeItem("playerLevel"); // 清空全部 // LocalStorageManager.clear(); // 判断是否存在 if (LocalStorageManager.hasKey("playerName")) { console.log("playerName 存在"); } } /** * 存储数据到本地 * @param key 键名 * @param value 值(会自动序列化为 JSON) */ public static setItem(key: string, value: any): void { Laya.LocalStorage.setItem(key, JSON.stringify(value)); } /** * 获取本地存储的数据 * @param key 键名 * @returns 解析后的对象或原始字符串,不存在返回 null */ public static getItem(key: string): T | null { const data = Laya.LocalStorage.getItem(key); if (data === null) return null; try { return JSON.parse(data) as T; } catch (e) { // 如果不是 JSON 格式,直接返回原始字符串 return data as any; } } /** * 删除指定键的本地数据 * @param key 键名 */ public static removeItem(key: string): void { Laya.LocalStorage.removeItem(key); } /** * 清空所有本地存储数据 */ public static clear(): void { Laya.LocalStorage.clear(); } /** * 获取所有存储的键名 * @returns 键名数组 */ public static getKeys(): string[] { const rawStorage = Laya.LocalStorage as any; const length = Laya.LocalStorage.length; const keys: string[] = []; for (let i = 0; i < length; i++) { const key = rawStorage.key ? rawStorage.key(i) : null; if (key) { keys.push(key); } } return keys; } /** * 检查是否存在某个键 * @param key 键名 * @returns 是否存在 */ public static hasKey(key: string): boolean { const keys = this.getKeys(); return keys.indexOf(key) !== -1; } }