cc.sys.localStorage.setItem 为 boolean 值,返回却是字符串类型

在使用 cc.sys.localStorage.setItem(key, value); 的时候被坑了一下,我存进去的时候是 Boolean 类型,取出来的时候是 string 类型,我使用 Ts 定义的布尔类型的能保存 string 而且没有报错。最后在浏览器输出文字的颜色不一样使用 typeof 输出了一下类型才发现的。

解决方法:

   public static getTypeUnlock(index: number) {
        let key = `${index}`;
        let unlock: boolean = false, item;

        item = cc.sys.localStorage.getItem(key);

        if (!item) {
            StorageManager.setItem(key, false);
            return false;
        }

        if (item == `false` || item == false) {
            unlock = false;
        }

        if (item == `true` || item == true) {
            unlock = true;
        }

        return unlock;
    }

    public static setItem(key: string, value: any) {
        cc.sys.localStorage.setItem(key, value);
    }

不知道大佬有没有更好的解决方法

直接用0和1不行么

根据你的提议改进了一下,像这样么

public static getTypeUnlock(index: number) {
        let key = `${index}`;
        let item;

        item = cc.sys.localStorage.getItem(key);

        if (!item) {
            StorageManager.setItem(key, 0);
            return false;
        }

        return item == 1;

    }

public static setTypeUnlock(index: number) {
        StorageManager.setItem(`${index}`, 1);
    }

是接口的问题,setItem和getItem就是只支持string(web)。
可以看一下文档
https://developer.mozilla.org/en-US/docs/Web/API/Storage/setItem

改进一下,Boolean() 方法会自动把 1 转成 true,把 0、null 和 undefined 转成 false 。
!!cc.sys.localStorage.getItem(${index}`) 也是同样的效果。

    public static getTypeUnlock(index: number) {
        return Boolean(cc.sys.localStorage.getItem(${index}`));
    }

    public static setTypeUnlock(index: number) {
        cc.sys.localStorage.setItem(`${index}`, 1);
    }

抓住一只逛论坛的崽

使用JSON就可以了

请问要怎么使用呢,有参考吗?


image
我是这样封装的存储类

1赞