HTML5本地存储和变量类型 [英] HTML5 Local Storage and Variable Types

查看:164
本文介绍了HTML5本地存储和变量类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为HTML5中的本地存储进行一些测试。注意我使用的是Safari 6.0.2,因为似乎很多网络引擎处理不同的方法。

I was just working on some tests for Local Storage in HTML5. Note I used Safari 6.0.2, as it seems many web-engines handle their methods different.

如果我这样做:

localStorage.setItem('subTotal', Number(12345)); // I know, it's redundant :)
var varType = typeof localStorage.getItem('subTotal');

alert(varType);

您现在会想;这是一个数字!但不是没有..看起来,即使使用类型转换,HTML5本地存储在插入时将所有变量类型转换为字符串。这很有趣,因为在使用开发工具时,它会在引号之间显示字符串值,但不会显示数字。也许是Inspector窗格剥离引号。

You would now think; It's a Number!. But no it's not.. It seems, even with type casting, that HTML5 Local Storage converts all variable types to Strings when inserting them. It's funny tho, because when using the Development Tools it shows String values between quotes, but not the Numbers. Maybe it's the Inspector pane that strips the quotes tho.

我已经在jQuery中有一个旧的自动typeCasting函数,但我总是厌倦这些情况,因为0和0是的,仍然可以弄得一团糟。

I already have an old automatic typeCasting function in jQuery, yet I'm always weary of these cases, as 0 and false, can still make a mess of things.

任何人都知道localStorage。* Library是否有设置来维护变量类型?

Anyone know if the localStorage.* Library has a setting to maintain the Variable Types?

推荐答案

您应该先将它们转换为JSON:

You should convert them to JSON first:

localStorage.setItem( 'subTotal', JSON.stringify(12345) );

然后,在检索项目时,解析JSON:

Then, when retrieving your item, parse the JSON:

JSON.parse( localStorage.getItem('subTotal') );

这是小提琴: http://jsfiddle.net/hD9dF/

为了便于使用,请创建你自己的包装:

For easier usage, create your own wrapper:

var myLocalStorage = {
    set: function (item, value) {
        localStorage.setItem( item, JSON.stringify(value) );
    },
    get: function (item) {
        return JSON.parse( localStorage.getItem(item) );
    }
};

这是小提琴: http://jsfiddle.net/hD9dF/1/

这篇关于HTML5本地存储和变量类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆